解决WaitForSingleObject阻塞UI线程的问题

清泛编译
WaitForSingleObjec 等待线程结束时会阻塞UI线程,导致界面不响应鼠标操作。
解决原理:等待过程中对消息队列中消息进行转发处理。

代码如下:
// 等待线程运行结束,WaitForSingleObject会阻塞UI线程
	MSG msg;
	DWORD dwRet;
	while (TRUE)  
	{
		//wait for m_hThread to be over,and wait for
		//QS_ALLINPUT(Any message is in the queue)
		dwRet = MsgWaitForMultipleObjects(1, &hThread, FALSE, INFINITE, QS_ALLINPUT);
		switch(dwRet)
		{
		case WAIT_OBJECT_0:
			break; //break the loop
		case WAIT_OBJECT_0 + 1:
			//get the message from Queue
			//and dispatch it to specific window
			PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
			DispatchMessage(&msg);
			continue;
		default:
			break; // unexpected failure
		}
		break;
	}

	//显示主界面
	...
使用 MsgWaitForMultipleObjects代替 WaitForSingleObject, 这个函数即可以等待信号(thread,event,mutex等等),也可以等待指定类型的消息(MSG),函数声明如下:
DWORD WINAPI MsgWaitForMultipleObjects(
        __in                         DWORD nCount, //number of objects to be wait
        __in                         const HANDLE* pHandles, //An array of object handles.
        __in                         BOOL bWaitAll, //If this parameter is TRUE, the function returns when the states
                                                    //of all objects in the pHandles array have been set to signaled
                                                    //and an message has been received.
        __in                         DWORD dwMilliseconds, //time-out interva
        __in                         DWORD dwWakeMask //the type of message to be wait
      );
参数dwWakeMask定义了要等待的消息的类型。

至此,问题完美解决。若要更详细的了解解决过程可参考:http://blog.csdn.net/silvervi/article/details/5874212

WaitForSingleObject 阻塞 UI线程

分享到:
评论加载中,请稍后...
创APP如搭积木 - 创意无限,梦想即时!
回到顶部