C# lock and monitor example

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.

C# Locking Example

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);
}
C# Monitor Enter Exit example

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.

  • Monitor.Enter()

    Acquire exclusive lock on specified object

  • Monitor.TryEnter()

    Try to acquire exclusive lock on specified object

  • Monitor.Wait()

    Wait method is used, to release the lock on an object, allow other threads to lock and access the object.

  • Monitor.Exit()
  • Monitor.Pules()

    This method notifies a thread in waiting queue about the change of locked object’s state.

  • Monitor.PulesAll()

You may be interested in following posts

 
C# mutex and semaphore example
.Net C# Programming Tutorials
Online Tutorials
C# .net Interview Questions Answers
.Net C# Examples | Join .Net C# Course