WaitForSingleObject times out too fast

I have this piece of code in a secondary thread:

DWORD result = WaitForSingleObject(myhandle,10000);
if(result == WAIT_OBJECT_0){
    AfxMessageBox(_T(...));
}
else if(result  == WAIT_TIMEOUT){

    AfxMessageBox(_T("Timeout"));
}

Sometimes, not always, the timeout will get called almost as soon as the WaitForSingleObject is called (not even 1s delay).

Am I doing something wrong ? Any suggestions for more stable alternatives ?


EDIT:

myhandle is created inside a class constructor as:

myhandle = CreateEvent(NULL,FALSE,FALSE,_T("myhandle"));

it would get called by another function:

SetEvent(myhandle);

The point is it works when I do the SetEvent, the problem is that it sometimes times out as soon as the WaitForSingleObject is called, even though it should wait 10s.


Do you really need/want a named event? Typically this is only required for inter-process concurrency control.

If you have multiple instances of this class they will all use the same event - see the docs for CreateEvent about calling for a named object that already exists.

It may be that all you need to do is remove the name here. This allows each class instance to have its own Event object and behaviour should be more predictable.


WaitForSingleObject will not wait the whole 10 seconds. It will wait for the first of:

  • The timeout value is elapsed
  • The event is signaled
  • The handle becomes invalid (closed in another thread)
  • If the event is set when you call WaitForSingleObject , condition #2 is true from the start and WaitForSingleObject returns immediatly.

    If you want to always wait 10 seconds, you should use code like this :

    //Always wait 10 seconds
    Sleep(10000); 
    
    //Test the event without waiting
    if(WaitForSingleObject(myhandle, 0) == WAIT_OBJECT_0) {
        AfxMessageBox(_T("Event was set in the last 10 secondes"));
    } else {
        AfxMessageBox(_T("Timeout"));
    }
    

    Took awhile but the problem actually was that the program sometimes did multiple calls to WaitForSingleObject . So it's a previous call that is timing out.

    Solution is to use WaitForMultipleObjects and set a cancelling event in the case it is known that the first event won't be set, so the timer is cancelled before is it re-invoked.

    链接地址: http://www.djcxy.com/p/62470.html

    上一篇: Windows操作系统能够从唤醒定时器唤醒多久?

    下一篇: WaitForSingleObject超时太快