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:
Thread 1 - USING LOCKS Thread 1 - releasing LOCKS Thread 0 - USING LOCKS Thread 0 - releasing LOCKS Thread 2 - USING LOCKS Thread 2 - Releasing LOCKS
Sanfoundry Global Education & Learning Series – 1000 C# Programs.
advertisement
If you wish to look at all C# Programming examples, go to 1000 C# Programs.
Related Posts:
- Practice MCA MCQs
- Check C# Books
- Practice Computer Science MCQs
- Check MCA Books
- Apply for Computer Science Internship