gpt4 book ai didi

windows - 了解 MsgWaitForMultipleObjects

转载 作者:可可西里 更新时间:2023-11-01 12:45:06 30 4
gpt4 key购买 nike

我有一个主要的 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,
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
}
}

关于windows - 了解 MsgWaitForMultipleObjects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1461378/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com