輸出結果 有時候,輸出結果是: 測試結果: 1 WaitForAll 不會阻塞主線程。 2 100 個 TTask 不會創建100個線程,不用寫代碼就可得到 【線程池】 一樣的功能! 3 無法判斷 Task 全部結束?? 4 線程中涉及到 【介面】時要多註意! 測試環境: win10 + delph ...
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; Button2: TButton; Button3: TButton; Button4: TButton; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); private procedure TaskProc(Sender: TObject); function FutureEvent(Sender: TObject): string; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses System.Threading, System.SyncObjs, System.Diagnostics; procedure TForm1.Button1Click(Sender: TObject); var ATask: ITask; begin ATask := TTask.Run(Self, Form1.TaskProc); ATask.Start; //阻塞至線程結束 ATask.Wait; end; procedure TForm1.Button2Click(Sender: TObject); var ATask: IFuture<string>; begin ATask := TTask.Future<string>(function: string begin TThread.Sleep(3000); Result := DateTimeToStr(Now); end); //阻塞至線程結束 Caption := ATask.Value; end; procedure TForm1.Button3Click(Sender: TObject); var ATask: IFuture<string>; begin ATask := TTask.Future<string>(Self, FutureEvent); //阻塞至線程結束 Caption := ATask.Value; end; procedure TForm1.Button4Click(Sender: TObject); var TaskArray: TArray<ITask>; I: Integer; begin SetLength(TaskArray, 5); for I := Low(TaskArray) to High(TaskArray) do TaskArray[I] := TTask.Run(procedure begin TThread.Sleep(1000); end); //阻塞至線程結束 TTask.WaitForAll(TaskArray); ShowMessage('ok'); end; procedure TForm1.FormCreate(Sender: TObject); begin ReportMemoryLeaksOnShutdown := True; end; function TForm1.FutureEvent(Sender: TObject): string; begin Result := DateTimeToStr(Now); end; procedure TForm1.TaskProc(Sender: TObject); var I: Integer; begin TThread.Sleep(3000); for I := 0 to 10 do TThread.Queue(nil, procedure begin Memo1.Lines.Add(Sender.ClassName); end); end; end.