In the previous article, we talked about “Introduction to Monitor Class In C#”. In this article, we will discuss the LOCK statement.
The LOCK statement is the most popular mutual-exclusive thread synchronization construct. You will be surprised when we dive deep into the details.
LOCK Statement
Basically, LOCK is a reserved keyword that is recognized by the C# compiler. It provides thread synchronization for a shared resource in case of execution in the critical section area and helps to avoid problems related to race conditions.
In order to use LOCK, you need to define a critical section area and wrap a LOCK around it. This will prevent threads from accessing shared resources at the same time.
How to use the LOCK statement is shown in the code below.
As you can see, the above code prevents the race condition problem by wrapping the LOCK statement around the critical section area. Also, it is best to use a private reference type to provide a lock state (_LOCKREF). So do not use public reference instance, the "this" keyword or interned string type; They may cause a deadlock.
Let’s understand how it works basically; Threads enter one by one into the code block, i.e. it accepts the thread into the critical section and executes the block with a single thread, then releases the thread. This means that all the other threads must wait and halt the execution until the locked section is released. And this cycle will continue in the same way.
Under The Hood
In fact, the LOCK statement is syntactic sugar. This means that when the C# compiler compiles code into the IL language, some keywords are converted into more complex code. In this way, it provides efficiency (providing ease of use).
In the code below you can see our IL (Microsoft Intermediate Language) code. It is very interesting that LOCK is converted to a Monitor class!
If the above IL code is not clear, you can check line 16, which declares System.Threading.Monitor::Enter(object, bool&). As you can see the LOCK statement is converting to Monitor class. Also the line 77 declares System.Threading.Monitor::Exit(object) which provides release lock state.
So, let’s look at the above IL code as C# code. The code declared below is similar to the code above (our previous method is wrapped by the Monitor class):
As you can see, try + finally blocks and Monitor class are used. Also, the LockTaken pattern is used to release only the locked ones (for more details).
Conclusion
The LOCK statement is a mutual-exclusive thread synchronization construct (because it uses the Monitor class). Also, this is syntactic sugar in C# that improves usability.
If you want to learn more about the Monitor class, you can check it out.
Stay Tuned!