Synchronization in C#
Introduction of Synchronization- Synchronization is particularly important when threads access the same data; it’s surprisingly easy to run aground in this area.Synchronization constructs can be divided into four categories:
- Simple blocking methods
- Locking constructs
- Signaling constructs
- No blocking synchronization constructs
using System;
using System.Threading;
namespace CSharpThreadExample
{
class Program
{
static void Main(string[] arg)
{
Console.WriteLine("-----> Multiple Threads ---->");
Printer p=new Printer();
Thread[] Threads=new Thread[3];
for(int i=0;i<3;i++)
{
Threads[i]=new Thread(new ThreadStart(p.PrintNumbers));
Threads[i].Name="Child "+i;
}
foreach(Thread t in Threads)
t.Start();
Console.ReadLine();
}
}
class Printer
{
public void PrintNumbers()
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(100);
Console.Write(i + ",");
}
Console.WriteLine();
}
}
} |
Why we use Lock keyword- lock(object) is used to synchronize the shared object.
Syntax:
lock (objecttobelocked)
{
objecttobelocked.somemethod();
}
Syntax:
lock (objecttobelocked)
{
objecttobelocked.somemethod();
}
- objecttobelocked is the object reference which is used by more than one thread to call the method on that object.
- The lock keyword requires us to specify a token (an object reference) that must be acquired by a thread to enter within the lock scope.
Using of Monitor- The lock scope actually resolves to the Monitor class after being processed by the C# compiler. Lock keyword is just a notation for using System.Threading.Monitor class.
using System;
using System.Threading;
namespace CSharpThreadExample
{
class Program
{
static void Main(string[] arg)
{
Console.WriteLine(" -----> Multiple Threads ----->");
Printer p = new Printer();
Thread[] Threads = new Thread[3];
for (int i = 0; i < 3; i++)
{
Threads[i] = new Thread(new ThreadStart(p.PrintNumbers));
Threads[i].Name = "Child " + i;
}
foreach (Thread t in Threads)
t.Start();
Console.ReadLine();
}
}
class Printer
{
public void PrintNumbers()
{
Monitor.Enter(this);
try
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(100);
Console.Write(i + ",");
}
Console.WriteLine();
}
finally
{
Monitor.Exit(this);
}
}
}
} |
Nice information about synchronization in C# my sincere thanks for sharing this post Please Continue to share this post
ReplyDeleteDot Net Training in Chennai
really nice blog has been shared by you. before i read this blog i didn't have any knowledge about this but now i got some knowledge about this so keep on sharing such kind of an interesting blogs.
ReplyDeletedotnet training in chennai
really you have posted an informative blog. before i read this blog i didn't have any knowledge about this but now i got some knowledge so keep on sharing such kind of an interesting blogs.
ReplyDeletedotnet training in chennai