WaitForSingleObject function is usually used to wait a response of another process or thread. Most common usage is like the following code.

WaitForSingleObject(object, INFINITE);

Although it is really simple and useful, it blocks all messages until the function returned. Therefore, the application using this function acts as if it is an unresponsive applcation like applications that are hangged.

Thus, I added a message pumping feature to the WaitForSingleObject API.
The function assumes that the user uses WaitForSingleObject function with INFINITE parameter. Since it supports the message pumping feature, it allows you to wait until the object signaled with very responsive user interface.

(I know that using thread is much better than this function. However, the problem is that thread is somewhat tedious work and sometimes managing thread just for very short code is quite burden for people)

void WaitForSingleObjectWithMsgPump(HANDLE hHandle)
{
DWORD dwRet;
DWORD dwFailedCnt = 0;
while(1) {
dwRet = WaitForSingleObject(hHandle, 1);
switch( dwRet ) {
case WAIT_TIMEOUT:
// not released - let it go
dwFailedCnt = 0;
break;
case WAIT_ABANDONED:
// released
return ;
break;
case WAIT_OBJECT_0:
// released
return ;
break;
case WAIT_FAILED:
// ? 
// if failed statues are repated over 5 times, 
// consider it as released
dwFailedCnt++;
if( dwFailedCnt > 4 ) {
return ;
}
break;
}

// pump message
PumpMsg();
Sleep(1);
}
}

+ Recent posts