还在苦苦敲代码开发APP?你out啦! 试试积木搭建APP吧~

解决WaitForSingleObject阻塞UI线程的问题

来源:清泛编译     2016-11-09 11:23:36    人气:     我有话说( 0 人参与)

WaitForSingleObjec 等待线程结束时会阻塞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线程

注:本文为本站或本站会员原创优质内容,版权属于原作者及清泛网所有,
欢迎转载,转载时须注明版权并添加来源链接,谢谢合作! (编辑:admin)
分享到: