Monitor class: In C#, the Monitor class provides a wait based synchronization mechanism that allows only one thread to access a critical section of code at a time to avoid the race condition. Here all the other threads have to wait and halt the execution until the locked object is released.
The Monitor.Enter method is used to acquire an exclusive lock on the object whereas Monitor.Exit method is used to release the locked object.
In order to use the Monitor class in a multithreading , we first need to import the System.Threading namespace.
This post series we will go through the understanding of the lock statement, monitor, mutex, and semaphore available in C#.
All of these classes provide a synchronization mechanism to protect the shared code or resources in a multithreadedapplication.
Let’s first understand the lock statement in C#.
C# Lock Statement
Lock Statement: In C#, the lock is a synchronization mechanism that allows only one thread to access a specified piece of code or a common field at a time.
It is mainly used to achieve an exclusive lock to avoid inconsistent output while reading and writing to a common variable in a multithreaded environment.
Generally, the lock keyword is placed around a critical section of code, where we want to allow only one thread to access the resource at a time. All the other threads have to wait and halt the execution until the locked object is released.
Pictorial representation of mutual exclusion of lock