了解MsgWaitForMultipleObjects

我有一个主要的gui线程,我想保持响应用户的行动,如移动对话框,resize等,而我有一个后台线程做一些任务。 在过去,我使用WaitForSingleObject超时,以便在完成后台线程等待时处理GUI事件。 我最近阅读了关于MsgWaitForMultipleObjects的文章,这个文章看起来解决了我有点干净的问题。

有人能告诉我在下面的代码中的错误和我要去哪里错了吗? 当我点击button启动线程时,gui没有反应。 我做了一个对话框的应用程序,正在播放主要的UI线程。 我有一个button来启动一个线程,并使用MsgWaitForMultipleObjects等待线程句柄,但是当线程完成/发送信号时,允许所有的消息最终被处理。

谢谢。

UINT MyThreadProc( LPVOID pParam ) { ThreadData* pObject = (ThreadData*)pParam; if (pObject == NULL || !pObject->IsKindOf(RUNTIME_CLASS(ThreadData))) return 1; // Do some processing. int x = 0; while (x++ < 5000) { for (int i=0; i<50000; i++) double sum = sqrt((double)i+1) * sqrt((double)i+2); } return 0; } 

button处理程序

 void Cmsgwait_demoDlg::OnBnClickedBtnStartThread() { m_pThreadData = new ThreadData; CWinThread* pWorkThread = AfxBeginThread(MyThreadProc, m_pThreadData); m_status.SetWindowText("Status: Waiting for thread to complete."); HANDLE handles[] = { pWorkThread->m_hThread }; DWORD ret = 0; do { ret = MsgWaitForMultipleObjects(1, handles, FALSE, INFINITE, QS_ALLINPUT); if (ret == WAIT_OBJECT_0) { m_status.SetWindowText("Status: Thread completed."); } else if (WAIT_IO_COMPLETION) { m_status.SetWindowText("Status: User mode APC queued."); } else if (WAIT_FAILED) { m_status.SetWindowText("Status: Wait failed"); } } while (ret != WAIT_OBJECT_0 && ret != WAIT_FAILED); } 

Solutions Collecting From Web of "了解MsgWaitForMultipleObjects"

您没有处理UI线程的传入消息,请查看Raymond的博客 (也请参阅此处 )以获取示例。

  while (true) { switch (MsgWaitForMultipleObjects(1, &h, FALSE, INFINITE, QS_ALLINPUT)) { case WAIT_OBJECT_0: DoSomethingWith(h); // event has been signalled break; case WAIT_OBJECT_0+1: // we have a message - peek and dispatch it while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { // TODO: must handle WM_QUIT; see Raymond's blog for details TranslateMessage(&msg); DispatchMessage(&msg); } break; default: return FALSE; // unexpected failure } }