lock
is a wrapper for Monitor.Enter
and Monitor.Exit
:
The
lock
keyword callsEnter
at the start of the block andExit
at the end of the block. From the former’s documentation:
From the documentation for Monitor.Enter
:
It is legal for the same thread to invoke
Enter
more than once without it blocking; however, an equal number ofExit
calls must be invoked before other threads waiting on the object will unblock.
Because the calls to Enter
and Exit
are paired, your code pattern has well defined behaviour.
Note, however, that lock
is not guaranteed to be an exception-less construct:
A
ThreadInterruptedException
is thrown ifInterrupt
interrupts a thread that is waiting to enter alock
statement.