C# - Thread Lock with Example?

Threading lock in C#: Here, we are going to learn how to lock a thread in C#? By Nidhi Last updated : March 29, 2023

Thread Locking

To implement thread locking, we will implement a mutual-exclusion lock to resolve the problem of the critical section. Here we block a critical section (set of statements) and execute statements and then release the lock.

C# program for thread locking

/*
 *  Demonstrate thread lock using C# program
 */

using System;
using System.Threading;

class LockDemo {
  static readonly object _object = new object();

  static void ThreadMethod() {
    lock(_object) {
      Thread.Sleep(100);
      Console.WriteLine(DateTime.Now);
    }
  }
  
  static void Main() {
    int loop = 0;

    while (loop < 5) {
      ThreadStart T = new ThreadStart(ThreadMethod);
      new Thread(T).Start();
      loop++;
    }
  }
}

Output

8/13/2020 8:14:54 PM
8/13/2020 8:14:54 PM
8/13/2020 8:14:55 PM
8/13/2020 8:14:55 PM
8/13/2020 8:14:55 PM
Press any key to continue . . .

Explanation

In the above program, we created a LockDemo class that contains two static methods ThreadMethod() and Main(). In the ThreadMethod(), we used mutual exclusive lock using lock keyword and Thread.Sleep() method is used to pause the thread execution. In the Main() method we created threads in the while loop.

C# Thread Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.