Delphi4技术内幕中提到 Delpih VCL线程是不安全的 要在线程中调用VCL的方法可以用TThread类实现
TThread有两个好处
1.提供了Synchronize函数,可以从一个线程中调用VCL
2.它提共了线程局部存储器(thread local storeage)
SynChronize 是TThread中的一个方法,可以用它封装对要调用VCL方法的调用
Delphi Help里有例子
This example shows how to call a button抯 click method in a thread-safe manner:
procedure TMyThread.PushTheButton;
begin
Button1.Click();
end;
procedure TMyThread.Execute;
begin
...
Synchronize(PushTheButton);
...
end;
这是唯一一个能在线程中调用VCL的方法,作用:使线程临时成为应用主程序的一部分
当一个程序在线程中不能访问VCL,解决的方法:SynChronize(ThreadMethod);
unit Unit3;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TMainForm = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TMyThread = class(TThread)
protected
procedure execute;overload;
procedure CallVclMethod;
end;
var
MainForm: TMainForm;
implementation
uses Unit4;
{$R *.dfm}
{ TMyThread }
procedure TMyThread.CallVclMethod;
begin
ChildForm := TChildForm.Create(Application);
ChildForm.Show;
ChildForm.Update;
end;
procedure TMyThread.execute;
begin
Synchronize(CallVclMethod);
end;
procedure TMainForm.Button1Click(Sender: TObject);
var
MyFunc:TMyThread;
begin
MyFunc := TMyThread.Create(false);
MyFunc.execute;
MyFunc.Free;
end;
end.
实际作用是暂时结束当前线程,并使它成为你应用程序中的一部分,在这段时间内就可调用VCL方法,当结束访向VCL后,中断程序中同步代码
SynChronize使线程与应程程序具有同步性