我想用 postmessage() 向 TObject 实例发送一条消息,但是在线程终止后,程序不会进入方法 HandleThreadCompletion。
const
WM_THREAD_COMPLETE = WM_USER + 5437;
TObject 实例 (TMaster) 包含线程对象的标识符
type
TMaster = class(TObject)
private
...
Fslave_search_thread : Tsrch_slave_thread;
fMsgHandlerHWND : HWND;
function start_slvsearch_th: integer;
procedure HandleThreadCompletion(var Message: TMessage);
...
public
...
end;
constructor TMaster.Create (aNode: TTreeNode; aName, anIP, aMAC: string);
begin
...
fMsgHandlerHWND := AllocateHWnd(HandleThreadCompletion);
...
end;
我释放并清除 TMaster.HandleThreadCompletion() 中的线程
procedure TMaster.HandleThreadCompletion(var Message: TMessage);
begin
if message.msg = WM_THREAD_COMPLETE then begin
if Assigned(Fslave_search_thread) then
begin
Fslave_search_thread.WaitFor;
Fslave_search_thread.Free;
Fslave_search_thread := nil;
...
end
end else
message.result := DefWindowProc(fMsgHandlerHWND, Message.Msg, Message.wParam, Message.lParam) ;
end;
在此处创建线程(暂停),填充一些字段而不是启动它(恢复)。
function TMaster.start_slvsearch_th: integer;
var
i: integer;
begin
if not Assigned(Fslave_search_thread) then begin
...
Fslave_search_thread := Tsrch_slave_thread.Create(true);
...
with Fslave_search_thread do
begin
master := self;
master_HWND := self.fMsgHandlerHWND;
FreeOnTerminate := False;
Resume;
...
end;
end;
终止时(从外部设置终止标志或循环结束),发送消息:
procedure Tsrch_slave_thread.Execute;
begin
while master.CMD_LISTCNT = 1 do
begin
...
if terminated then break;
end;
PostMessage(master_HWND, WM_THREAD_COMPLETE, 0, 0);
...
end;
http://members.upclive.hu/ikt/thread_terminate_test_postmessage.zip