Monitor.Enter : Monitor « System.Threading « C# / C Sharp by API






Monitor.Enter

  

using System;
using System.Threading;


public class EnterExit {
    private int result = 0;

    public void NonCriticalSection() {
        Console.WriteLine("Entered Thread " + Thread.CurrentThread.GetHashCode());

        for (int i = 1; i <= 5; i++) {
            Console.WriteLine("Result = " + result++ + "  ThreadID "
                              + Thread.CurrentThread.GetHashCode());
            Thread.Sleep(1000);
        }

        Console.WriteLine("Exiting Thread " + Thread.CurrentThread.GetHashCode());
    }
    public void CriticalSection() {
        Monitor.Enter(this);
        Console.WriteLine("Entered Thread " + Thread.CurrentThread.GetHashCode());

        for (int i = 1; i <= 5; i++) {
            Console.WriteLine("Result = " + result++ + "  ThreadID " +
                              Thread.CurrentThread.GetHashCode());
            Thread.Sleep(1000);
        }
        Console.WriteLine("Exiting Thread " + Thread.CurrentThread.GetHashCode());

        Monitor.Exit(this);
    }

    public static void Main(String[] args) {
        EnterExit e = new EnterExit();

        Thread nt1 = new Thread(new ThreadStart(e.NonCriticalSection));
        nt1.Start();

        Thread nt2 = new Thread(new ThreadStart(e.NonCriticalSection));
        nt2.Start();

        Thread ct1 = new Thread(new ThreadStart(e.CriticalSection));
        ct1.Start();

        Thread ct2 = new Thread(new ThreadStart(e.CriticalSection));
        ct2.Start();
    }
}

   
    
  








Related examples in the same category

1.Monitor.Exit
2.Monitor.Pulse
3.Monitor.TryEnter