Users Online

· Guests Online: 105

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

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.

  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

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.89 seconds
10,832,943 unique visits