Delphi中多線程用消息實現(xiàn)VCL數(shù)據(jù)同步顯示 Lanno Ckeeke 2006-5-12 概述: delphi中嚴格區(qū)分主線程和子主線程,主線程負責GUI的更新,子線程負責數(shù)據(jù)運算,當數(shù)據(jù)運行完畢后,子線程可以向主線程式發(fā)送消息,以便通知其將VCL中的數(shù)據(jù)更新。 實現(xiàn): 關(guān)鍵在于消息的發(fā)送及接收。在消息結(jié)構(gòu)Tmessage中wParam和lParam類型為Longint,而指針類型也定義為Longint,可以通過此指針來傳遞自己所感興趣的數(shù)據(jù)。如傳遞字符數(shù)組: 數(shù)組定義: const MAX_LEN = 260; szName : array[0..MAX_LEN] of Char; 消息發(fā)送方式: PostMessage(Form1.Handle,WM_UPDATEDATA,Integer(PChar(@szName)),0); 消息接收方式: procedure TForm1.WMUpdateData(var msg : TMessage); begin self.ShowData.Items.Add(PChar(msg.WParam)); end; 子線程中定義兩個數(shù)據(jù)類型: public szName : array[0..MAX_LEN] of Char; nIndex : Integer; 完整代碼: 子線程類: unit TChildThread; interface uses Classes,Messages,Windows,SysUtils;//添加的使用文件 const MAX_LEN = 260; type TChildThreads = class(TThread) private { Private declarations } protected procedure Execute; override; public szName : array[0..MAX_LEN] of Char; nIndex : Integer; end; implementation uses Unit1; { Important: Methods and properties of objects in VCL or CLX can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure TChildThread.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; } { TChildThread } procedure TChildThreads.Execute; begin { Place thread code here } PostMessage(Form1.Handle,WM_UPDATEDATA,Integer(PChar(@szName)),0); //注意類型轉(zhuǎn)化部分的寫法 end; end. 主線程代碼: unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls; const WM_UPDATEDATA = WM_USER + 100;//自定義的消息,利用此消息來實現(xiàn)對GUI的更新 type TForm1 = class(TForm) ControlPannel: TGroupBox; StartThreads: TButton; TabControl1: TTabControl; SingleThread: TRadioButton; MultipleThreads: TRadioButton; StopThreads: TButton; ShowData: TListBox; ShowError: TListBox; Initialize: TButton; Cleanup: TButton; //GUI更新的消息處理函數(shù)聲明 procedure WMUpdateData(var msg : TMessage);message WM_UPDATEDATA; procedure StartThreadsClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation uses TChildThread; {$R *.dfm} //消息函數(shù)定義 procedure TForm1.WMUpdateData(var msg : TMessage); begin self.ShowData.Items.Add(PChar(msg.WParam)); end; procedure TForm1.StartThreadsClick(Sender: TObject); var oChildThread : array[0..1000] of TChildThreads; i : Integer; begin For i := 0 to 1000 do begin oChildThread[i] := TChildThreads.Create(true); //向VCL中發(fā)送的數(shù)據(jù) strcopy(@oChildThread[i].szName,PChar('Child' + IntToStr(i))); oChildThread[i].nIndex := i; oChildThread[i].Resume; end; end; end. |
|