[ACCEPTED]-Does C# Monitor.Wait() suffer from spurious wakeups?-multithreading

Accepted answer
Score: 89

Joe Duffy's "Concurrent Programming On Windows" mentions this (P311-312, P598). This 30 bit is interesting:

Note that in all of the 29 above examples, threads must be resilient 28 to something called spurious wake-ups - code 27 that uses condition variables should remain 26 correct and lively even in cases where it 25 is awoken prematurely, that is, before the 24 condition being sought has been established. This 23 is not because the implementation will actually 22 do such things (although some implementations 21 on other platforms like Java and Pthreads 20 are known to do so), nor because code will 19 wake threads intentionally when it's unnecessary, but 18 rather due to the fact that there is no 17 guarantee around when a thread that has 16 been awakened will become scheduled. Condition 15 variables are not fair. It's possible - and 14 even likely - that another thread will acquire 13 the associated lock and make the condition 12 false again before the awakened thread has 11 a chance to reacquire the lock and return 10 to the critical region.

He then gives the 9 normal pattern for a while loop testing 8 the condition.

I would say that from this 7 it's reasonable to expect that Monitor.Wait won't normally 6 wake you prematurely, and that if you absolutely 5 know that nothing else can have changed the 4 condition then you might be able to get away 3 without the condition loop: but that it's 2 safer to include it anyway, just in case 1 your logic is inaccurate.

More Related questions