本文整理自网络,侵删。
uses System.Threading;
TTask只接受没有参数的过程,但现实开发中经常需要给任务传递特定参数。
先看看常规的写法
var tasks: TArray; i: Integer;begin SetLength(tasks, 3); for i := 0 to 2 do begin tasks[i] := TTask.Run( procedure begin OutputdebugString(PChar(IntToStr(i))); end); end; TTask.WaitForAll(tasks);end;这样就形成了一个闭包,匿名方法中变量i的值是没有保障的。最后,我通过增加一个包装类来解决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; procedure Button1Click(Sender: TObject); end; var Form1: TForm1; implementation uses System.Threading; type TMyTask = class private _id: Integer; procedure Execute; public constructor Create(id: Integer); function Start: ITask; end; {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject);var list: TObjectList; tasks: TArray; i: Integer;begin list := TObjectList.Create; list.Add(TMyTask.Create(1)); list.Add(TMyTask.Create(2)); list.Add(TMyTask.Create(3)); SetLength(tasks, list.Count); for i := 0 to list.Count - 1 do begin tasks[i] := list[i].Start; end; TTask.WaitForAll(tasks); list.Free;end; { TMyTask } constructor TMyTask.Create(id: Integer);begin _id := id;end; procedure TMyTask.Execute;begin OutputdebugString(PChar(IntToStr(_id)));end; function TMyTask.Start: ITask;begin Result := TTask.Run(Execute);end; end.这样就实现了给任务传递参数的目的。――――――――――――――――
原文链接:https://blog.csdn.net/aqtata/article/details/77197030
相关阅读 >>
Delphi applicationevents1 webbrowser1屏蔽右键菜单
Delphi windows 编程[2] - 学习窗体生成的过程二
Delphi 如何使用sendmessage发送后台组合键消息(ctrl+xxx)
Delphi 判断uefi与 legacy bios启动模式
Delphi xe intraweb 程序在iis下的发布详细教程
Delphi实现进制转化(2进制,8进制,10进制,16进制)
更多相关阅读请进入《Delphi》频道 >>