我有一个主要的gui线程,我想要保持对用户操作的响应,例如移动对话框,调整大小等,同时我有一个后台线程执行某项任务.在过去,我使用WaitForSingleObject并超时,以便在等待后台线程完成时处理gui事件.我最近读到了MsgWaitForMultipleObjects,它看起来正在解决我有点清洁的问题.
有人可以告诉我以下代码中的错误&我在哪里错了?当我单击按钮启动线程时,gui没有响应.我用一个在主ui线程上播放的avi创建了一个对话框应用程序.我有一个按钮来启动一个线程并使用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; }
按钮处理程序
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); }
您没有处理UI线程的传入消息,请在
look at Raymond’s blog(也参见
here)获取样本.
while (true) { switch (MsgWaitForMultipleObjects(1,&h,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,PM_REMOVE)) { // TODO: must handle WM_QUIT; see Raymond's blog for details TranslateMessage(&msg); DispatchMessage(&msg); } break; default: return FALSE; // unexpected failure } }