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
advertisement
If you wish to look at all C# Programming examples, go to 1000 C# Programs.
Next Steps:
- Get Free Certificate of Merit in C# Programming
- Participate in C# Programming Certification Contest
- Become a Top Ranker in C# Programming
- Take C# Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Buy Computer Science Books
- Practice Computer Science MCQs
- Buy C# Books
- Apply for Computer Science Internship
- Apply for C# Internship