Home »
.Net »
C# Programs
C# program to demonstrate thread lock
Threading lock in C#: Here, we are going to learn how to lock a thread in C#?
Submitted by Nidhi, on August 16, 2020
To solve the above problem, here 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.
Program:
/*
* 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 »