WaitForSingleObject crashes too fast

I have this piece of code in a secondary stream:

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

    AfxMessageBox(_T("Timeout"));
}

Sometimes, not always, a timeout will be called almost immediately after calling WaitForSingleObject (not even a delay of 1 s).

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


EDIT:

myhandle is created inside the class constructor as:

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

it will be called by another function:

SetEvent(myhandle);

The fact is that this works when I do a SetEvent, the problem is that it sometimes expires as soon as WaitForSingleObject is called, although it should wait 10 seconds.

+3
source share
3 answers

The time came, but in fact the problem was that the program sometimes made several calls to WaitForSingleObject. So this is the previous call that is disconnected.

WaitForMultipleObjects , , , , .

0

/ ? concurrency.

, - . docs CreateEvent , .

, , , . Event, .

+1

WaitForSingleObject 10 . :

  • ( )

, WaitForSingleObject, №2 WaitForSingleObject .

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

//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"));
}
0
source

All Articles