我无法通过拉撒路中的匿名方式传递参数 我使用了 delphi 示例,但它们不起作用
procedure hi(i:integer);
begin
form1.caption:=inttostr(i);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
begin
for i:=1 to 4 do
TThread.CreateAnonymousThread(
TProcedure(@hi(i));
).Start;
end;
我尝试了这个例子,它不起作用
procedure TForm1.Button1Click(Sender: TObject);
var
Thread: TThread;
Value: Integer;
begin
Value := 42;
Thread := TThread.CreateAnonymousThread(
procedure
begin
hi('hello');
end
);
Thread.Start;
end;
不幸的是,Lazarus 不支持带有附加参数的 CreateAnonymousThread。但您可以自己为任何类型的参数编写类似的代码。
{$mode objfpc}
{$MODESWITCH ADVANCEDRECORDS}
type
generic TParProc<T> = procedure (par : T);
{ TAnonymousThreadWithPars }
generic TAnonymousThreadWithPars<T> = class (TThread)
private
fProc : specialize TParProc<T>;
fParam : T;
public
constructor Create(f: specialize TParProc<T>; const par : T);
procedure Execute; override;
class function CreateAnonymousThreadWithParams(f: specialize TParProc<T>; const par : T): TThread;
end;
{ TAnonymousThreadWithPars }
constructor TAnonymousThreadWithPars.Create(f: specialize TParProc<T>;
const par: T);
begin
inherited Create(True);
fProc:= f;
fParam:= par;
FreeOnTerminate:= true;
end;
procedure TAnonymousThreadWithPars.Execute;
begin
fProc(fParam);
end;
class function TAnonymousThreadWithPars.CreateAnonymousThreadWithParams(
f: specialize TParProc<T>; const par: T): TThread;
begin
Result := specialize TAnonymousThreadWithPars<T>.Create(f, par);
end;
procedure proc(i : integer);
begin
WriteLn('hello ', i);
end;
var
i : integer;
begin
for i := 0 to 4 do
specialize TAnonymousThreadWithPars<Integer>.CreateAnonymousThreadWithParams(@Proc, i).Start;
end.