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