The Monitor
key (or the lock
keyword) is used to enter and exit the critical section. A critical section is a block of code that is guaranteed to be executed alternately with respect to any other critical section defined by the same object reference ( Monitor.Enter
parameter). In other words, two or more threads executing critical sections defined by the same object reference should do this in such a way as to exclude their simultaneous execution. There is no guarantee that threads will do this in any particular order though.
For example, if we mark two critical section blocks of your code A
and B
with two threads as T1
and T2
, then any of the admissible below visualizes representations of the execution sequences.
T1: AAA . . . A . AA . T2: . . . BBB . B . . B
or
T1: . AA . . AA T2: B . . BB . .
or
T1: AAAAAAA . T2: . . . . . . . B
or
T1: A . A . A . A . A . T2: . B . B . B . B . B
The range of possible alternating permutations is infinite. I just showed you an infinitely small subset. It so happened that only the last permutation will lead to the fact that your program will work as you expected. Of course, that permutation is extremely unlikely, you introduce other mechanisms to make it happen.
You mentioned that Thread.Sleep(1)
changed the behavior of your program. This is because it affects how the OS schedules thread execution. Thread.Sleep(1)
is actually a special case that causes the calling thread to give its time slice to another thread of any processor. It was not clear to me where you put this call into your program, so I can not comment too much on why it gave the desired behavior. But I can say that this is mostly random.
In addition, I must indicate that you have a rather large error in this program. When you exit the while
through break
, you Monitor.Exit
call to Monitor.Exit
, which will leave the lock in the acquired state. It is much better to use the lock
keyword because it will wrap Monitor.Enter
and Monitor.Exit
in a try-finally
block, which ensures that the lock is always released.
source share