M
monster
Unregistered / Unconfirmed
GUEST, unregistred user!
我的程序原来退出时,有时候按Ctrl+Alt+Delete能发现它的"尸体".
经调试,终于发现释放时如果线程处于挂起状态(Suspended),就在WaitFor里陷入了无限等待.
MyThread.Terminate;
MyThread.WaitFor;
//可能陷入无限等待
MyThread.Free;
跟踪代码:
Unit Classes;
function TThread.WaitFor: LongWord;
var
Msg: TMsg;
H: THandle;
begin
H := FHandle;
if GetCurrentThreadID = MainThreadID then
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!!!!! 如果进入时线程处于挂起状态(Suspended)
//!!!!!! 循环一次就陷入无限等待
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
while MsgWaitForMultipleObjects(1, H, False, INFINITE, QS_SENDMESSAGE) = WAIT_OBJECT_0 + 1do
PeekMessage(Msg, 0, 0, 0, PM_NOREMOVE)
else
WaitForSingleObject(H, INFINITE);
GetExitCodeThread(H, Result);
end;
把我的释放线程部分改成这样
MyThread.Terminate;
if MyThread.Suspended then
MyThread.Resume;
MyThread.WaitFor;
MyThread.Free;
一切都OK,OK!!!
我的疑问是: 为什么会这样? Thread的源码为什么就不判断一下? 释放线程到底该怎样才最好???
经调试,终于发现释放时如果线程处于挂起状态(Suspended),就在WaitFor里陷入了无限等待.
MyThread.Terminate;
MyThread.WaitFor;
//可能陷入无限等待
MyThread.Free;
跟踪代码:
Unit Classes;
function TThread.WaitFor: LongWord;
var
Msg: TMsg;
H: THandle;
begin
H := FHandle;
if GetCurrentThreadID = MainThreadID then
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!!!!! 如果进入时线程处于挂起状态(Suspended)
//!!!!!! 循环一次就陷入无限等待
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
while MsgWaitForMultipleObjects(1, H, False, INFINITE, QS_SENDMESSAGE) = WAIT_OBJECT_0 + 1do
PeekMessage(Msg, 0, 0, 0, PM_NOREMOVE)
else
WaitForSingleObject(H, INFINITE);
GetExitCodeThread(H, Result);
end;
把我的释放线程部分改成这样
MyThread.Terminate;
if MyThread.Suspended then
MyThread.Resume;
MyThread.WaitFor;
MyThread.Free;
一切都OK,OK!!!
我的疑问是: 为什么会这样? Thread的源码为什么就不判断一下? 释放线程到底该怎样才最好???