program main; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils, OtlParallel; begin Parallel.Async(procedure var i: Integer; begin for I := 0 to 100 do Writeln(Format('No.%d', [i])); end); Writeln('執行一'); Sleep(100); Writeln('執行二'); Sleep(100); Writeln('執行三'); Sleep(100); Readln; end.
輸出結果:函數
程序很是簡單spa
引用OtlParallel.pas單元 建立一個匿名函數控制檯輸出1..10 code
跟進源碼看到下面兩個函數orm
procedure Parallel.Async(task: TProc; taskConfig: IOmniTaskConfig); TOmniTaskDelegate = reference to procedure(const task: IOmniTask);//TOmniTaskDelegate 任務委託聲明
procedure Parallel.Async(task: TOmniTaskDelegate; taskConfig: IOmniTaskConfig);
第一個函數Async 接受一個TProc的匿名函數, taskConfig默認爲nil (IOmniTaskConfig應該是設置任務的一些屬性後面在研究)blog
實際內部調用用了Parallel.Async(task: TOmniTaskDelegate; taskConfig: IOmniTaskConfig) 源碼
方便使用it
class procedure Parallel.Async(task: TProc; taskConfig: IOmniTaskConfig); begin Async( procedure (const omniTask: IOmniTask) begin task; end, taskConfig ); end; { Parallel.Async } class procedure Parallel.Async(task: TOmniTaskDelegate; taskConfig: IOmniTaskConfig); var omniTask : IOmniTaskControl; terminated: TOmniTaskConfigTerminated; begin if assigned(taskConfig) then (taskConfig as IOmniTaskConfigInternal).DetachTerminated(terminated); omniTask := CreateTask(task, 'Parallel.Async').Unobserved.OnTerminated( procedure (const task: IOmniTaskControl) var exc: Exception; begin terminated.Call(task); exc := task.DetachException; if assigned(exc) then raise exc; end ); Parallel.ApplyConfig(taskConfig, omniTask); omniTask.Unobserved; omniTask.Schedule(GetPool(taskConfig)); end; { Parallel.Async }