Delphi xe TTask 执行多线程,其实...完成任务后,一直在后台执行东西的。
uses System.Threading; //定义变量线程池 lpThreadPool: TThreadPool; //定义事件 procedure TForm1.log( lgoInfo : string ); begin Memo1.Lines.Add( '' ); Memo1.Lines.Add( FormatDateTime( 'yyyy-mm-dd hh:mm:ss', Now ) + ' ' + trim( lgoInfo ) ); {$IFDEF DEBUG} CodeSite.SendMsg('TForm1.log'); {$ENDIF} end; procedure TForm1.FormCreate(Sender: TObject); begin lpThreadPool := TThreadPool.Create(); lpThreadPool.SetMaxWorkerThreads(1); lpThreadPool.SetMinWorkerThreads(3); {$IFDEF DEBUG} CodeSite.SendMsg('TForm1.FormCreate'); {$ENDIF} end; procedure TForm1.Button1Click(Sender: TObject); var lpTask: ITask; begin lpTask := TTask.Create( procedure() var i: integer; begin for i := 1 to 10 do TThread.Synchronize(nil, procedure begin Memo1.Lines.Add(IntToStr(i)); {$IFDEF DEBUG} CodeSite.SendMsg(' lpTask := TTask.Create'); {$ENDIF} end); end, lpThreadPool); lpTask.Start(); lpTask := TTask.Create( procedure() var i: integer; begin for i := 11 to 20 do TThread.Synchronize(nil, procedure begin Memo1.Lines.Add(IntToStr(i)); end); end, lpThreadPool); lpTask.Start(); lpTask := TTask.Create( procedure() var i: integer; begin for i := 21 to 30 do TThread.Synchronize(nil, procedure begin Memo1.Lines.Add(IntToStr(i)); end); end, lpThreadPool); lpTask.Start(); end;
等TTask任务执行完毕后,线程池的状态函数 ——TThreadPoolMonitor.GrowThreadPoolIfStarved 会一直执行。