Monitor.TryEnter : Monitor « Thread « C# / C Sharp






Monitor.TryEnter

 


using System;
using System.Threading;

public class TryEnter {

    public void CriticalSection() {
        bool b = Monitor.TryEnter(this, 1000);
        Console.WriteLine("Thread " +
                          Thread.CurrentThread.GetHashCode() +
                          " TryEnter Value " + b);

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

        Monitor.Exit(this);
    }

    public static void Main() {
        TryEnter a = new TryEnter();
        Thread t1 = new Thread(new ThreadStart(a.CriticalSection));
        Thread t2 = new Thread(new ThreadStart(a.CriticalSection));
        t1.Start();
        t2.Start();
    }
}
 

 








Related examples in the same category

1.Monitor: Enter
2.Monitor.Pulse