tags:

views:

20

answers:

0

I am using the following function to wait on an event handle for certain amount of time while keep processing the incoming message. However, while I am waiting, the CPU usage goes to almost 50% for a dual-core CPU. Is there anything wrong with my code?

MsgWaitForMultipleObjects keeps returning WAIT_OBJECT_0+1 if I trace the code. I see some WM_TIMER messages. I didn't set any timer myself. That's probably part of MFC implementation. I also see some undocumented messages 0xc03e and have no idea what that is. But I have no reason to believe the application is wasting all the CPU processing all the idle messages. If I let my application idle without calling this function, the CPU usage is 0%.

Thanks a lot for any help.

UINT MsgWaitSObj(HANDLE hEvent, UINT nTimeout)
{

UINT r;
MSG msg;
CTime StopTime;
if (nTimeout!=INFINITE) 
{
    StopTime=CTime::GetCurrentTime()+CTimeSpan(0, 0, 0, nTimeout);
}
while (1)
{
    if (nTimeout!=INFINITE) 
    {
        CTimeSpan ts=StopTime-CTime::GetCurrentTime();
        if (ts.GetTotalSeconds()<0) return WAIT_TIMEOUT;
        nTimeout=ts.GetTotalSeconds()*1000;
    }
    r=MsgWaitForMultipleObjects(1,&hEvent,0,nTimeout,QS_ALLINPUT);
    if (r==WAIT_OBJECT_0 || r==WAIT_TIMEOUT) break;  
    if (r==WAIT_OBJECT_0+1)
    {
        while (PeekMessage(&msg, NULL, 0, 0,PM_REMOVE)) 
        {
            TranslateMessage(&msg); 
            DispatchMessage(&msg);
        }
    }
}

return r;

}