Does C# Monitor.Wait() suffer from spurious wakeups?

Java's Object.wait() warns against "spurious wakeups" but C#'s Monitor.wait() doesn't seem to mention it at all.

Seeing how Mono is implemented on top of Linux, and Linux has spurious wakeups, shouldn't this be documented somewhere?


Solution 1:

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

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

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

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