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.
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论