Introduction
Lock statement is very useful statement in
c# language. Lock statement hold the object and then process to
synchronization way. It is use to multi threads application. If current
thread execute a lock of code then this code compile without interruption by
another thread.
The lock
statement obtains a mutual exclusion lock for a given object so that one
thread executes the code block at a time and exits the code block after
releasing the lock.
Example
using
System;
using
System.Threading;
namespace
lock_statement_in_c_sharp
{
class
lock_class
//create class
{
static
readonly
object obj =
new
object();
//create readonly object
public
static
void display()
//create function
{
lock (obj)
//lock readonly object
{
Thread.Sleep(400);
//sleep 400 milliseconds
Console.WriteLine("Welcome");
}
}
}
class
Program
{
static
void Main(string[]
args)
{
ThreadStart
str = new
ThreadStart(lock_class.display);
//create thread
for (int
i = 0; i < 5; i++)
{
new
Thread(str).Start();
//display function call by the
thread
}
}
}
}
Output: