Learn how to use Lock and monitor in C#. Lock and monitor are basically used in multithreading.
When we work on any multithreading application, as a developer it’s our duty to take care of each thread we create, because in every thread we have some code base to execute, that code base may consume which is also can be accessed from other thread.
In .net framework, we have some mechanism for thread safety using Lock and Monitor.
MyObject _obj=new MyObject(); lock (_obj) { // Your code }
Note: We should use Lock
on a Reference Type only, Not on any Value Type.
Here is a quick example of how you can lock a list object.
In this example, we will see after locking a list object, if list object value cannot be altered! Just to test if locking working properly.
static Student _student = new Student(); public static void LockObject() { // lock on the object, sleep for 100 milliseconds. lock (_student) { _student.Address = "South Kolkata"; Thread.Sleep(500); Console.WriteLine(Environment.TickCount); Console.WriteLine(_student.Address); } }
Now we write different threads to execute above method
public static void Example() { for (int i = 0; i < 10; i++) { Thread t1 = new Thread(new ThreadStart(LockObject)); t1.Start(); Thread t2 = new Thread(new ThreadStart(AlterObject)); t2.Start(); } }
Now let’s try to alter the object
public static void AlterObject() { // try to alter the object. _student.Address = "Sanfrancisco"; _objectLst.Add($"updated old value-{Environment.TickCount}"); Console.WriteLine(_student.Address); }
Monitor class provides the mechanism for ensuring that only one thread at a time can execute certain piece of code
static Student _student = new Student(); public static void MonitorObject() { Monitor.Enter(_student); try { //Here we can do some file update or database update _student.Address = "New York"; Console.WriteLine(Environment.TickCount); Console.WriteLine(_student.Address); } finally { Monitor.Exit(_student); } } public static void Example() { for (int i = 0; i < 10; i++) { Thread t1 = new Thread(new ThreadStart(MonitorObject)); t1.Start(); } }
Monitor Class provides some static methods to ensure synchronizes access to any object.
Acquire exclusive lock on specified object
Try to acquire exclusive lock on specified object
Wait method is used, to release the lock on an object, allow other threads to lock and access the object.
This method notifies a thread in waiting queue about the change of locked object’s state.
You may be interested in following posts