多线程 Win32 GUI 消息循环 [英] Multithreaded Win32 GUI message loop

查看:40
本文介绍了多线程 Win32 GUI 消息循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候需要在多线程应用中使用这种类型的修改消息循环?

When do you need to use this type of modified message loop in multithreaded application?

DWORD nWaitCount;
HANDLE hWaitArray[4];
BOOL quit;
int exitCode;
while (!quit)
{
   MSG msg;
   int rc;
   rc = MsgWaitForMultipleObjects(nWaitCount, hWaitArray, FALSE, INFINITE,QS_ALLINPUT);

   if (rc == WAIT_OBJECT_O + nWaitCount)
   {
       while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
       {
        if (msg.message == WM_QUIT)
        {
            quit = TRUE;
            exitCode = msg.wParam;
            break;
        }
        TranslateMessage(&msg);
        DispatchMessage(&msg);
       }
   }
   else if (rc >= WAIT_OBJECT_0 && rc < WAIT_OBJECT_0 + nwaitCount)
   {
       int nlndex = rc - WAIT_OBJECT_0;
   }
   else if (rc >= WAIT_ABANDONED_0 && rc < WAIT_ABANDONED_0+ nWaitCount)
   {
       int nlndex = rc - WAIT_ABANDONED_O;
   }
}

推荐答案

希望永远不会.但是,当您希望 UI 线程阻塞同步对象时,您必须编写这种代码.不允许阻止 UI 线程,Windows 会阻止您调用 WaitForMultipleObjects().原因是它很可能导致死锁.

Hopefully never. But it is the kind of code you have to write when you want the UI thread to block on synchronization objects. A UI thread is not permitted to block, Windows prevents you from calling WaitForMultipleObjects(). The reason is that it is very likely to cause deadlock.

这样做的原因是 COM.COM 在 Windows 中无处不在,最常见的例子是剪贴板、拖放和外壳对话框.COM 使用消息循环对从工作线程对驻留在 STA(单线程单元)上的 COM 对象进行的接口方法调用进行编组.如果 STA 线程未发送消息,则调用将无法完成.无法完成的调用是导致死锁的第一要素.添加等待工作线程完成的 UI 线程,确保死锁.

The reason for that is COM. COM is everywhere in Windows, the most common examples are the clipboard, drag+drop and the shell dialogs. COM marshals interface method calls made from a worker thread for COM objects that live on the STA (Single Threaded Apartment) by using the message loop. If the STA thread isn't pumping messages then the call won't complete. And calls that can't complete are ingredient number one for deadlock. Add a UI thread that waits for the worker thread to complete and deadlock is assured.

您可以通过让工作线程使用 PostMessage() 向 UI 线程通知发生重要事件来避免此类代码.

You avoid this kind of code by having a worker thread use PostMessage() to signal the UI thread that something important happened.

这篇关于多线程 Win32 GUI 消息循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆