The correct way to view Monitor.Wait and Monitor.Pulse / PulseAll not a wait facility, but rather (for Wait ) as a means of letting the system know that the code is in a wait loop that cannot exit until something interesting changes , and (for Pulse / PulseAll ) as a means of letting the system know that the code has just changed something that could cause an exit condition, some other thread wait cycle, You need to be able to replace all occurrences of Wait with Sleep(0) and continues to work correctly (although it is much less effective in the district result of the CPU time is constantly changing test conditions that have not changed).
For this mechanism to work, you must avoid the possibility of the following sequence:
The code in the wait loop checks the condition when it is not satisfied.
Code in another thread changes the condition so that it is satisfied.
The code in this other thread blocks the lock (which no one else is waiting for).
The code in the wait loop executes Wait because its condition was not met.
The Wait method requires that the wait thread have a lock, as this is the only way to ensure that the expected condition does not change between the time it spent and the time the code executes Wait . The Pulse method requires blocking, because the only way to make sure that if another thread has completed Wait by itself, Pulse will not happen until another thread actually does. Note that using Wait inside a lock does not guarantee that it is used correctly, but there is no way that using Wait outside a lock can be correct.
The Wait / Pulse construct really works quite well if both sides work together. The biggest drawbacks of the IMHO design are: (1) there is no mechanism for the thread to wait until any of several objects are pulsed; (2) even if one of them "shuts down" the object in such a way that all future wait cycles should leave immediately (perhaps by checking the exit flag), the only way to ensure that any Wait that was sent by the stream to receive a Pulse is in order to get a lock, perhaps a long time to wait for its availability.
supercat
source share