delphi——用线程创建一个窗体笔记
???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;interfaceusesWindows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,Dialogs, StdCtrls;typeTMainForm = class(TForm)Button1: TButton;procedure Button1Click(Sender: TObject);private{ Private declarations }public{ Public declarations }end;TMyThread = class(TThread)protectedprocedure execute;overload;procedure CallVclMethod;end;varMainForm: TMainForm;implementationuses Unit4;{$R *.dfm}{ TMyThread }procedure TMyThread.CallVclMethod; beginChildForm := TChildForm.Create(Application);ChildForm.Show;ChildForm.Update; end;procedure TMyThread.execute; beginSynchronize(CallVclMethod); end;procedure TMainForm.Button1Click(Sender: TObject); varMyFunc:TMyThread; beginMyFunc := TMyThread.Create(false);MyFunc.execute;MyFunc.Free; end;end.實際作用是暫時結束當前線程,并使它成為你應用程序中的一部分,在這段時間內就可調用VCL方法,當結束訪向VCL后,中斷程序中同步代碼
SynChronize使線程與應程程序具有同步性
轉載于:https://www.cnblogs.com/pengshao/archive/2011/04/16/2018457.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的delphi——用线程创建一个窗体笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 转:两种转换mysql数据编码的方法-l
- 下一篇: 深入 理解 Statement 和 Pr