unit UDept;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Forms;
Const
MSG_UpdateSuccess = WM_User + 1;
type
//数据同步线程
TThreadUpdateData = class(TThread)
public
lSendHandle :HWND;
//线程创建过程,参数CreateSuspended表示创建时线程是否挂起,
constructor Create(CreateSuspended: Boolean);
//线程销毁时,发送线程终结命令,取消线程挂起状态,等待线程执行完毕后,销毁
destructor Destroy; override;
protected
procedure Execute; override;
private
end;
TFrmDept = class(TForm)
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
procedure MsgUpdateSuccess(var Message :TMessage); message MSG_UpdateSuccess;
public
{ Public declarations }
lUpdateThread :TThreadUpdateData ;
end;
var
FrmDept: TFrmDept;
implementation
{$R *.dfm}
procedure TFrmDept.FormShow(Sender: TObject);
begin
lUpdateThread := TThreadUpdateData.Create(True);
lUpdateThread.lSendhandle := Self.Handle;
end;
procedure TFrmDept.FormShow(Sender: TObject);
begin
lUpdateThread := TThreadUpdateData.Create(True);
lUpdateThread.lSendhandle := Self.Handle;
end;
procedure TFrmDept.MsgUpdateSuccess(var Message :TMessage);
begin
if Message.WParam = 1 then
//Do Somthing
end;
procedure TFrmDept.FormClose(Sender: TObject; var Action: TCloseAction);
begin
lUpdateThread.Destroy;
end;
constructor TThreadUpdateData.Create(CreateSuspended: Boolean);
begin
inherited Create(CreateSuspended);
end;
destructor TThreadUpdateData.Destroy;
begin
Terminate;
Resume;
WaitFor;
inherited;
end;
procedure TThreadUpdateData.Execute;
begin
inherited;
while not Terminated do
begin
// Do Somthing;
SendMessage(lSendHandle, MSG_UpdateSuccess, 1, 0);
if Terminated then Exit;
Suspend;
end;
end;
end.
认为的运行情况:
子线程发送消息MSG_UpdateSuccess,然后等待消息返回,返回后子线程挂起,等待下次调用
主线程收到消息进行处理,处理完之后返回。
其他处理方式:
在应用程序中设置一个全局变量,子线程执行成功之后,给该变量赋值。
应用程序中设置一个定时器,实时监测全局变量的状态,如果发现被赋值,执行某些操作后,将全局变量清零。
个人认为如果使用发送消息的方式没有副作用的话,使用该方法效率较高。