mfc 怎么找出WaitForMultipleObjects 哪个句柄无效 demo示例参考
时间: 2024-12-08 10:17:26 浏览: 71
MFC(Microsoft Foundation Classes)是Microsoft提供的Windows应用程序开发框架,它基于C++。`WaitForMultipleObjects`是一个系统函数,用于等待多个对象(如窗口、线程或其他同步事件)变为活动状态。在使用`WaitForMultipleObjects`时,如果某个句柄无效,可能导致函数返回错误结果。
下面是一个简单的MFC CWinApp中使用`WaitForMultipleObjects`的示例,并检查句柄是否有效:
```cpp
#include "afxwin.h"
// 假设我们有三个句柄数组hHandles[]
CWinThread *threads[3];
...
// 初始化句柄数组
for (int i = 0; i < 3; ++i) {
if (!threads[i]) { // 检查句柄是否为空
TRACE(traceAppMsg, 0, "Invalid handle at index %d", i);
// 这里可以抛出异常或者记录错误日志,然后退出等待
continue;
}
hHandles[i] = threads[i]->m_hThread; // 获取句柄
}
DWORD dwResult = ::WaitForMultipleObjects(
_countof(hHandles), // 数量
hHandles, // 句柄数组
FALSE, // 非阻塞模式
INFINITE // 最长时间无响应
);
if (dwResult == WAIT_FAILED) {
DWORD lastError = GetLastError();
TRACE(traceAppMsg, 0, "WaitForMultipleObjects failed with error: %u", lastError);
// 处理错误情况,例如句柄失效等
}
```
在这个例子中,首先检查每个`CWinThread`实例的句柄是否为空。如果发现无效句柄,程序会跳过这个句柄并继续检查下一个。如果`WaitForMultipleObjects`函数本身失败,还可以通过获取错误代码来确定问题来源。
阅读全文
相关推荐


















