Monitor.TryEnter : Monitor : Thread C# Source Code


Custom Search

C# Source Code » Thread » Monitor »

 

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();
    }
}
 

 
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Thread
» Monitor