示例代码
unit main;interfaceusesWinapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, doroutine;typeTForm3 = class(TForm)Button1: TButton;procedure Button1Click(Sender: TObject);procedure FormCreate(Sender: TObject);private{ Private declarations }public{ Public declarations }end;varForm3: TForm3;implementation{$R *.dfm}procedure doCompleted(task: TTask);
beginif TThread.Current.ThreadID = MainThreadID thenbeginShowMessage('主线程 执行了 完成回调');end else beginShowMessage('bg线程 执行了 完成回调');end;
end;procedure bgSmall(task: TTask);
begin//doSomeThing http 请求了,或其他 后台业务Sleep(10); //模拟做事//看下日志OutputDebugString(PChar(Format('线程ID: %s,做完了一个!', [TThread.Current.ThreadID.ToString])));
end;procedure bgBig(task: TTask);
begin//开启300个bg小协程做事,完成时做回调for var i := 1 to 300 dobegintask.bg(bgSmall).start;end;
end;procedure TForm3.Button1Click(Sender: TObject);
begin//开启一个大协程做事,做完 主线程 执行回调task.bg(bgBig).onCompleteUi(doCompleted).start;//task.bg(bgBig).onCompleteBg(doCompleted).start; 后台线程执行回调
end;procedure TForm3.FormCreate(Sender: TObject);
beginReportMemoryLeaksOnShutdown := True;
end;end.
效果图