Thread Lock in C#

In this article we’ll learn about Thread Lock in C#, how locks ensure the exclusive access to the shared resources. All we’ll discuss with the help of example.

When we are working with threads and multiple threads try to access some shared resources or one critical piece of code, in this case thread safety is required. We can use Lock and Monitor for exclusive locking and with the help of this of one thread is executing critical piece of code then another thread will wait until first thread will complete.

C# LOCK:

Lock provides the thread safety and avoid thread collision with each other. A lock statement takes a reference to an object which may be acquired by a thread. Until current thread is executing critical piece of code second thread have to wait until it competes.

Syntax

lock (Obj)
{
   // critical piece of code 
}

C# LOCK Code Sample:

namespace CodeConfigLocks
{
   public class Program
    {
        static void Main(string[] args)
        {
            // ShowMessage(1);
            Thread t1 = new Thread(ShowMessage);
            Thread t2 = new Thread(ShowMessage);
            Thread t3 = new Thread(ShowMessage);
            Thread t4 = new Thread(ShowMessage);
            t1.Start(1);
            t2.Start(2);
            t3.Start(3);
            t4.Start(4);
            Console.Read();
        }

        private static readonly object obj = new object();
        static void ShowMessage(object m)
        {
            lock (obj)     // this line of code will apply lock 
            {
                //split string chars and concatenate again using for loop
                string msg = "Welcome to our new method, Executing Thread " + Convert.ToString(m) + "  !\n";
                Thread.Sleep(100);
                string[] authorsList = msg.Split(' ');
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < authorsList.Length; i++)
                {
                    sb.Append(authorsList[i] + " ");

                }
                Console.WriteLine(sb.ToString());

            }
        }
    }
}

Output:

Thread Lock in C#

In above sample code all four threads execute in sequence, and all this happened because of “lock (obj)”. You can check by commenting out this line you will see the execution of thread will not be in sequence and this may case incorrect output from your program.

Nested Locking:

Nested thread LOCK can also be used as shown in below sample code. In this case object is unlocked only when the outermost lock statement has existed. Unlocking mechanism moves form inner LOCK to outer most LOCK.

lock (obj1)
  lock (obj2)
    lock (0bj3)
    {
        // critical piece of code
    }
  }
}

Key points of LOCKS

  • Do not LOCK anything Publicly accessible.
  • Lock applied only on a Reference Type, not a Value Type.
  • Avoid Excessive Locking or nested locking.
  • LOCK must be implemented with care else it can also create DEADLOCK.

Monitor:

In case of monitor only one thread may acquire a particular monitor at one time and other thread cannot interfere or execute the same piece of code and have to wait until first thread complete. Once the execution is completed it releases the lock and frees objects. Now second thread can acquire monitor on it. It starts with “Monitor.Enter()” method and exit with “Monitor.Exit()” method with in “Finally Block”.  

 

bool Islocked = false;
Object obj = new Object();
try
{
    Monitor.Enter(obj, ref Islocked);
    // critical piece of code 
}
finally
{
  if (locked)
  {
      Monitor.Exit(Obj);
  }
}

What is lock statement in VB.Net?

In C# it is LOCK but in VB.net it is SyncLock.

“SyncLock” STOP other threads from entering the block until any other thread is executing it.

Why does the lock object have to be static?

No, it is not mandatory to use a private static readonly object for locking in case of multi-threading. We can also use instance object.

How to lock several objects using LOCK?

If you want to lock two or more object, then you can do it using following approach.

lock (obj1)
{
    lock (obj2)
    {
      // your critical piece of code
    }
}

One simpler way to write above is

lock (obj1) lock (obj2)
    {
        // your critical piece of code
    }

In this article we tried to explain Thread Lock C# with Examples. I hope you enjoyed reading this article. For more information you can check out Microsoft learn.

For more information you can visit our C# Section for more such articles.

Leave a Reply

Your email address will not be published. Required fields are marked *