delphi Parallel의 Ttask 첫 번째 시도

7956 단어
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
  System.Generics.Collections;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    Memo2: TMemo;
    Memo3: TMemo;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private

  public
    { Public declarations }
  end;


var
  Form1: TForm1;



implementation

{$R *.dfm}

uses
  System.Threading, System.SyncObjs, System.Diagnostics;

procedure TForm1.Button1Click(Sender: TObject);
const
  C = 1000;
var
  TaskArray: array of ITask;
  I: Integer;
  ATask: ITask;
begin
  Button1.Enabled := False;

  Memo1.Clear;
  Memo2.Clear;
  Memo3.Clear;

  SetLength(TaskArray, C);

  for I := 0 to C - 1 do
  begin
    TaskArray[I] := TTask.Create(procedure
      var
        Id: string;
      begin
        Id := TThread.Current.ThreadID.ToString;
        TThread.Queue(nil, procedure
          begin
            if Memo1.Lines.IndexOf(Id)=-1 then
              Memo1.Lines.Add(Id);
            //Memo2.Lines.Add( IntToStr(Memo2.Lines.Count+1) );
          end);
      end);
    TaskArray[I].Start;
  end;

  TThread.CreateAnonymousThread(procedure
    var
      I: Integer;
      Task: ITask;
    J: Integer;
    begin
      I := C;
      while I > 0 do
      begin
        for Task in TaskArray do
          if Task.Status = TTaskStatus.Completed then
            Dec(I);
      end;

      TThread.Synchronize(nil, procedure
        begin
          Memo1.Lines.Add('OK');
          Button1.Enabled := True;
        end);

      //       
      for J := 0 to C - 1 do
        TaskArray[J] := nil;
     end).Start;

  if TTask.WaitForAll(TaskArray) then
    Memo1.Lines.Add('WaitForAll');
end;
procedure TForm1.FormCreate(Sender: TObject); begin ReportMemoryLeaksOnShutdown := True; end; end.

결과 내보내기
1 WaitForAll
2 7120
3 7064
4 7052
5 OK
6 3272

때때로 출력 결과는 다음과 같습니다.
1 WaitForAll
2 7064
3 7120
4 3272
5 7052
6 OK

테스트 결과:
1 WaitForAll은 기본 스레드를 차단하지 않습니다.
2 100개의 TTASk는 100개의 라인을 만들지 않습니다. 코드를 쓰지 않아도 [라인 풀]과 같은 기능을 얻을 수 있습니다!
3 Task 가 모두 종료되었는지 확인할 수 없습니다??
4 라인에서 [인터페이스]가 관련되었을 때 주의해야 합니다!
 
테스트 환경:
win10 + delphi 10.1 berlin

좋은 웹페이지 즐겨찾기