問題描述:
在監(jiān)控程序中,設(shè)計一監(jiān)控循環(huán)。
頭文件.h
HANDLE m_hEventExit;
CWinThread* m_pThread;
構(gòu)造函數(shù)中,創(chuàng)建該事件
m_hEventExit=CreateEvent(NULL, // 安全
TRUE, // 手動
FALSE, // 初始化為非信號模式
_T("Exit Event") // 線程名稱
);
在OnButtonThreadStart()中
{
if(!m_pThread)
{
ResetEvent(m_hEventExit);
m_ pThread = AfxBeginThread(MonitorThreadFunc, this);
}
}
MonitorThreadFunc 中需要修改主界面中的控件。
這時候如果在OnButtonThreadStop()中
{
SetEvent(m_hEventExit);
if(m_ pThread!= NULL)
{
TRACE0("The thread is still running.\n");
WaitForSingleObject(m_ pThread ->m_hThread, -1);
delete m_ pThread;
m_ pThread = NULL;
}
}
其中Wait行使主界面進(jìn)入等待狀態(tài),如果這時候工作線程執(zhí)行完了,可以順利退出,如果線程此時正在更新界面控件,就會陷入死鎖。
解決方法:
使用WaitThreadWithHandleMsg函數(shù),可以在等待線程結(jié)束的同時響應(yīng)消息。
為了使用方便,將該函數(shù)封裝了一下,使用的時候只需要調(diào)用一下。
int WINAPI WaitThreadWithHandleMsg(HANDLE hEventThread)


{
HRESULT hResult = S_FALSE;
BOOL bWait = TRUE;

while (bWait)

{
DWORD dwEvt = MsgWaitForMultipleObjects(1,&hEventThread,FALSE,INFINITE,QS_ALLINPUT);

switch(dwEvt)

{
case WAIT_OBJECT_0:
bWait = false;
hResult = TRUE;
break;
case WAIT_OBJECT_0 + 1:

{
MSG msg;
while(::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))

{
if (WM_CLOSE == msg.message || WM_QUIT == msg.message)

{
bWait = false;
break;
}
else

{
PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
break;
}
default: // WAIT_TIMEOUT WAIT_FAILED
bWait = false;
hResult = FALSE;
break;
}
} // end while

return hResult;
}