Open In App

How to Thread Lock Work in C#?

Improve
Improve
Like Article
Like
Save
Share
Report

C# makes the concurrent execution of a code possible with the help of threads. The namespace System. Threading which is pre-built in C# supports the use of threads. Typically we create threads for the concurrent execution of a program. But in certain cases we may not want our program to be run concurrently by more than 1 thread i.e. we want to prevent simultaneous access to a resource by multiple threads. The resource here may refer to a data type or variable that is created in the C# program.

Lock in C#:

To avoid the above condition, C# has an inbuilt keyword ‘lock’ that prevents simultaneous access to a resource by two threads. The syntax of lock keyword is shown below:

Syntax:

lock(name_of_object) 
statements_to_be_executed_after_lock

Note: It is important to make use of System.Threading namespace to implement threading and locking.

Working of C#:

Let us have a look at how the lock in C# works:

  • Use of a lock prevents the code block to be concurrently accessed by other threads when one thread is executing it.
  • The other threads that want to execute the code block in case of locking, must either wait or halt until first thread completes its execution.
  • Once a thread completes its execution, the lock is released and other threads can execute the code block.
  • The use of threads and locks makes programming convenient and improves execution.

The implementation of locks will be explained by an example. Let us first see a program without the use of locks.

Example 1: 

C#




using System;
// This namespace is necessary 
// to implement threading and
// locks
using System.Threading;
  
namespace No_Lock {
    public class no_lock {
      public static void Main(string[] args)
      {
          // Creating two threads on a code block func
          Thread a = new Thread(func);
          Thread b = new Thread(func);
          // Begin the execution of both threads using Start()
          a.Start();
          b.Start();
      }
  
      // This is the code block that is to be executed by
      // both the threads
      public static void func()
      {
          string str = "Hello World";
          for (int i = 0; i < str.Length; i++) {
              Console.Write(str[i]);
              Thread.Sleep(TimeSpan.FromSeconds(0.2));
          }
          Console.Write(" ");
      }
    }
}


Output: 

HHeelllloo  WWoorrlldd

The above program is a simple code where two threads execute a function which prints the characters of a string. As it can be seen from the output, the second thread begins its execution even when the first has not completed its execution.

Now let us see a program with the use of locks.

Example 2: 

C#




using System;
// This namespace is necessary 
// to implement threading and
// locks
using System.Threading;
  
namespace Locked_thread {
    public class locked_thread {
      // Creating an object that will 
      // be used to lock the thread
      public static readonly object locked = new object();
      // This is the code block that is
      // to be executed by
      // both the threads
      public static void func()
      {
          // This statement locks the thread 
          // when it begins execution
          lock(locked){
            string str = "Hello World";
            for (int i = 0; i < str.Length; i++) {
                Console.Write(str[i]);
            }
            Console.Write("\n");
          }
      }
        
      public static void Main(string[] args)
      {
          // Creating two threads on a code block func
          Thread a = new Thread(func);
          Thread b = new Thread(func);
          // Begin the execution of both
          // threads using Start()
          a.Start();
          b.Start();
      }
    }
}


Output: 

Hello World
Hello World

In this program, we need to create an object that will be responsible for locking. The statements to be executed are then written inside the block of this object. As we can see from the output that both the threads execute the code block one by one instead of concurrent execution when the thread lock is implemented.



Last Updated : 08 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads