C# Program to Demonstrate Monitor Lock with Lock Statement
Posted by Superadmin on August 11 2022 09:45:39

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.

  1. /*
  2.  * C# Program to Illustrate the Use of Monitor Lock with Lock Statement
  3.  */
  4. using System;
  5. using System.IO;
  6. using System.Threading;
  7. namespace monitorclass
  8. {
  9.     class Program
  10.     {
  11.         static object locker = new object();
  12.         static void ThreadMain()
  13.         {
  14.             Thread.Sleep(800);    // Simulate Some work
  15.             WriteToFile();          
  16.         }
  17.         static void WriteToFile()
  18.         {
  19.             String ThreadName = Thread.CurrentThread.Name;
  20.             Console.WriteLine("{0} USING LOCKS", ThreadName);
  21.             Monitor.Enter(locker);
  22.             try
  23.             {
  24.                 using (StreamWriter sw=new StreamWriter(@"D:\srip\sri.txt", true))
  25.                 {
  26.                     sw.WriteLine(ThreadName);
  27.                 }
  28.             }
  29.             catch (Exception ex)
  30.             {
  31.                 Console.WriteLine(ex.Message);
  32.             }
  33.             finally
  34.             {
  35.                 Monitor.Exit(locker);
  36.                 Console.WriteLine("{0} Releasing LOCKS", ThreadName);
  37.             }
  38.         }
  39.         static void Main(string[] args)
  40.         {
  41.             for (int i = 0; i < 3; i++)
  42.             {
  43.                 Thread thread = new Thread(new ThreadStart(ThreadMain));
  44.                 thread.Name = String.Concat("Thread - ", i);
  45.                 thread.Start();
  46.  
  47.             }
  48.             Console.Read();
  49.         }
  50.     }
  51. }

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