我有一个线程创建需要单线程单元的 COM 对象。
最初,该线程的 main 函数将其放入 WaitForMultipleObjects 循环中。显然这是一个问题,因为它阻止了 COM 消息泵的工作。
我将其替换为 MsgWaitForMultipleObjects 作为解决方案,但现在我遇到了一个问题:MsgWaitForMultipleObjects 有时(经常)返回 WAIT_FAILED,但没有设置错误。
该代码通过继续并尝试再次调用 MsgWaitForMultipleObjects 来处理 WAIT_FAILED 返回值。对 MsgWaitForMultipleObjects 的调用可能会返回 WAIT_FAILED 几次(我见过的最多的是 9 次),但随后它突然可以正常工作了。
编写代码是为了在函数出于正当理由返回 WAIT_FAILED 时可能会进入无限循环。我知道我应该解决这个问题,但目前我认为这是一种“解决方法”,因为 MsgWaitForMultipleObjects 调用最终会成功。
此代码正在 Windows 7、Vista 和 XP(所有 32 位、Windows 7 32 和 64 位)上进行测试。
有谁知道为什么会这样?
相关代码:
bool run = true;
while (run)
{
DWORD ret = MsgWaitForMultipleObjects(2, events, FALSE, INFINITE,
QS_ALLINPUT);
switch (ret)
{
case WAIT_OBJECT_0:
{
ResetEvent(events[0]);
ProcessWorkQueue();
break;
}
case WAIT_OBJECT_0 + 1:
{
run = false;
break;
}
case WAIT_OBJECT_0 + 2:
{
MSG msg;
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
DispatchMessage(&msg);
break;
}
case WAIT_FAILED:
{
Logger::Output(L"Wait failed in Notify::Run(), error is "
+ boost::lexical_cast<std::wstring>(GetLastError()));
}
}
}
示例输出为:
Wait failed in Notify::Run(), error is 0
Wait failed in Notify::Run(), error is 0
Wait failed in Notify::Run(), error is 0
Wait failed in Notify::Run(), error is 0
Wait failed in Notify::Run(), error is 0
Wait failed in Notify::Run(), error is 0
Wait failed in Notify::Run(), error is 0
Wait failed in Notify::Run(), error is 0
Wait failed in Notify::Run(), error is 0
// At this point, the wait succeeds
我相信 WAIT_FAILED 返回值仅在等待被消息打破后才会发生。