Its simpler than you think-
According to Microsoft:
The lock
keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.
The lock
keyword calls Enter
at the start of the block and Exit
at the end of the block. lock
keyword actually handles Monitor
class at back end.
For example:
private static readonly Object obj = new Object();
lock (obj)
{
// critical section
}
In the above code, first the thread enters a critical section, and then it will lock obj
. When another thread tries to enter, it will also try to lock obj
, which is already locked by the first thread. Second thread will have to wait for the first thread to release obj
. When the first thread leaves, then another thread will lock obj
and will enter the critical section.