c# thread lock |
C# THREAD LOCK
“C# thread lock is a process of locking of block of codes or resource to preventing the access of multiple threads for a same resource at a point of time”.
C# thread lock process play very important rule in multithreading ,when multiple user trying to access for a same resources of Data in Data Base System and Web Server System at a time.
Syntax of Thread locking
To lock the blocks of code we use the keyword ‘Lock (this)’ and place the codes
in-between starting and closing braces like given below, now once you lock the codes then that is accessable for only one thread at a time all the other thread have to wait in line to get acess to thoes code which is locked. C# thread lock syntax is
Lock (this)
{
Statements;
Or block of codes;
}
EXAMPLE OF THREAD LOCKING
Suppose an
example. That has a lock method accessing by different thread, make sure to add
directive above of namespace that is ‘System. Threading’.
using System.Threading;
namespace ThraedLock
{
class Program
{
public void ThreadLockdemo()
{
lock (this)
{
for (int i = 1; i <= 50; i++)
Console.WriteLine("Printing line
number " + i );
}
}
static void Main(string[] args)
{
Program p = new Program();
Thread t1 = new
Thread(p.ThreadLockdemo);
Thread t2 = new Thread(p.ThreadLockdemo);
Thread t3 = new
Thread(p.ThreadLockdemo);
t1.Start();
t2.Start();
t3.Start();
Console.ReadKey();
}
}
}
This program will program the line in sequence
otherwise without using lock threading sequence will disturbed run it and see
the outputs and then remove the lock body and see the output you will notice
the changes.
0 comments:
Post a Comment
Please do not enter any spam link in the comment box