Thread 1 - USING LOCKS Thread 1 - releasing LOCKS Thread 0 - USING LOCKS Thread 0 - releasing LOCKS Thread 2 - USING LOCKS Thread 2 - Releasing LOCKS
Users Online
· Guests Online: 105
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
Forum Threads
Newest Threads
No Threads created
Hottest Threads
No Threads created
Latest Articles
Articles Hierarchy
C# Program to Demonstrate Monitor Lock with Lock Statement
C# Program to Demonstrate Monitor Lock with Lock Statement
This C# Program Illustrates the Use of Monitor Lock with Lock Statement. Here A monitor is a mechanism for ensuring that only one thread at a time may be running a certain piece of code . A monitor has a lock, and only one thread at a time may acquire it.
Here is source code of the C# Program to Illustrate the Use of Monitor Lock with Lock Statement. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
-
/*
-
* C# Program to Illustrate the Use of Monitor Lock with Lock Statement
-
*/
-
using System;
-
using System.IO;
-
using System.Threading;
-
namespace monitorclass
-
{
-
class Program
-
{
-
static object locker = new object();
-
static void ThreadMain()
-
{
-
Thread.Sleep(800); // Simulate Some work
-
WriteToFile();
-
}
-
static void WriteToFile()
-
{
-
String ThreadName = Thread.CurrentThread.Name;
-
Console.WriteLine("{0} USING LOCKS", ThreadName);
-
Monitor.Enter(locker);
-
try
-
{
-
using (StreamWriter sw=new StreamWriter(@"D:\srip\sri.txt", true))
-
{
-
sw.WriteLine(ThreadName);
-
}
-
}
-
catch (Exception ex)
-
{
-
Console.WriteLine(ex.Message);
-
}
-
finally
-
{
-
Monitor.Exit(locker);
-
Console.WriteLine("{0} Releasing LOCKS", ThreadName);
-
}
-
}
-
static void Main(string[] args)
-
{
-
for (int i = 0; i < 3; i++)
-
{
-
Thread thread = new Thread(new ThreadStart(ThreadMain));
-
thread.Name = String.Concat("Thread - ", i);
-
thread.Start();
-
-
}
-
Console.Read();
-
}
-
}
-
}
Here is the output of the C# Program:
Comments
No Comments have been Posted.
Post Comment
Please Login to Post a Comment.