查看 的各种声明TThread.Synchronize()
。您正在尝试调用以 aTThreadMethod
作为输入的版本。 TThreadMethod
是无参数的:
TThreadMethod = procedure of object;
这就是为什么传球t.Proc
有效但传球t.Proc('foo')
无效的原因。
话虽如此,您完全在滥用TThread.Synchronize()
. 您无需创建TThread
对象即可使用Synchronize()
. 如果你确实创建了一个TThread
对象,让它真正做一些事情,就像这样:
type
TSendThread = class(TThread)
public
fStr: String;
procedure DoProc;
procedure Proc(const S: string);
protected
procedure Execute; override;
end;
procedure TSendThread.Execute;
begin
Proc('foo');
end;
procedure TSendThread.Proc(const S: string);
begin
fStr := S;
Synchronize(DoProc);
end;
procedure TSendThread.DoProc;
begin
ShowMessage(fStr);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
t : TSendThread;
begin
t := TSendThread.Create(False);
t.WaitFor;
t.Free;
end;
但是,因为您使用的是 XE4,所以Synchronize()
也支持匿名过程,这将TSendThread
在此示例中完全消除您的类,例如:
procedure TForm1.Button1Click(Sender: TObject);
begin
TThread.Synchronize(nil,
procedure
begin
ShowMessage('foo');
end
);
end;
更新:给出关于你真正想用你的线程做什么的新信息,你需要像这样去做:
type
TSendThread = class(TThread)
private
fURL, fMethod, fParam: string;
protected
procedure Execute; override;
public
constructor Create(aURL, aMethod, aParam: string);
end;
constructor TSendThread.Create(aURL, aMethod, aParam: string);
begin
inherited Create(False);
fURL := aUrl;
fMethod := aMethod;
fParam := aParam;
end;
procedure TSendThread.Execute;
begin
// use fURL, fMethod, and fParam as needed...
end;
procedure TForm1.Button1Click(Sender: TObject);
var
t : TSendThread;
begin
t := TSendThread.Create('url', 'method', 'param');
...
end;
或者像这样:
type
TSendThread = class(TThread)
private
fURL, fMethod, fParam: string;
procedure GetValues;
protected
procedure Execute; override;
end;
procedure TSendThread.GetValues;
begin
fURL := ...;
fMethod := ...;
fParam := ...;
end;
procedure TSendThread.Execute;
begin
Synchronize(GetValues);
// use fURL, fMethod, and fParam as needed...
end;
procedure TForm1.Button1Click(Sender: TObject);
var
t : TSendThread;
begin
t := TSendThread.Create(False);
...
end;