概述:
delphi中严格区分主线程和子主线程,主线程负责GUI的更新,子线程负责数据运算,当数据运行完毕后,子线程可以向主线程式发送消息,以便通知其将VCL中的数据更新。
实现:
关键在于消息的发送及接收。在消息结构Tmessage中wParam和lParam类型为Longint,而指针类型也定义为Longint,可以通过此指针来传递自己所感兴趣的数据。如传递字符数组:
数组定义:
const
MAX_LEN = 260;
szName : array[0..MAX_LEN] of Char;
|
消息发送方式:
PostMessage(Form1.Handle,WM_UPDATEDATA,Integer(PChar(@szName)),0);
消息接收方式:
procedure TForm1.WMUpdateData(var msg : TMessage);
begin
self.ShowData.Items.Add(PChar(msg.WParam));
end;
|
子线程中定义两个数据类型:
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);
//
注意类型转化部分的写法
end;
end.
|
主线程代码:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls;
const
WM_UPDATEDATA = WM_USER + 100;//
自定义的消息,利用此消息来实现对
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
更新的消息处理函数声明
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}
//
消息函数定义
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
中发送的数据
strcopy(@oChildThread[i].szName,PChar('Child' + IntToStr(i)));
oChildThread[i].nIndex := i;
oChildThread[i].Resume;
end;
end;
end.
|