Skip to content
Related Articles
Get the best out of our app
Open App

Related Articles

C# – Lock in Thread

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Multithreading is one of the powerful concepts of any programming language. It is basically thread-based multiprocessing. In this process, the program is divided into different parts and these parts are allowed to execute concurrently or simultaneously. The benefit of using multithreading in a program is that it maximizes the utilization of the CPU of our system. A thread is a lightweight sub-process that might share resources with another thread. That is why program using multithreading mechanism tends to consume less space. This varies with multitasking as in that case separate memory is allocated for different tasks. This article focuses upon demonstrating lock-in thread through C#. 

Lock in Thread

The lock statement is used to take the mutual-exclusion lock for a specified object. It executes a specified block and then releases the lock. The time during which the lock is active, the thread that holds the lock can again take and release the lock. Note that any other thread cannot access the lock and it waits unless the lock is released. 


lock (exp)


    // body


Here, exp is an expression of reference type.

Note: await operator cannot be used in the lock statement.

Example: In the below program, we are using a for-loop and at each step of the iteration, we are creating a new thread. Here, using the lock keyword we specify a statement block as a critical section by getting the mutual-exclusion lock for a specified object then executing a statement. Now the sleep() method has been used to pause the thread for a specific period of time then it will release the lock.


// C# program to illustrate lock in thread
using System;
using System.Threading;
class GFG{
// Creating a reference type object
static readonly object obj = new object();
static void Sample()
      // Lock statement block
          // Sleep the thread
          // Print the count
// Driver code
static public void Main()
      // Iterate using a for-loop
    for(int i = 0; i < 5; i++)
          // Create a new thread
        ThreadStart begin = new ThreadStart(Sample);
          // Start executing the thread
        new Thread(begin).Start();






My Personal Notes arrow_drop_up
Last Updated : 28 Jan, 2022
Like Article
Save Article
Similar Reads
Related Tutorials