Use the Mutex object: WaitOne : Mutex « Thread « C# / CSharp Tutorial






using System;
using System.Threading;

class MainClass
{
  private static int Runs = 0;

  static Mutex mtx = new Mutex(false, "RunsMutex");

  public static void CountUp() 
  {
    while (Runs < 10)
    {
      // acquire the mutex
      mtx.WaitOne();
      int Temp = Runs;
      Temp++;
      Console.WriteLine(Thread.CurrentThread.Name + " " + Temp);
      Thread.Sleep(1000);
      Runs = Temp;
      // release the mutex
      mtx.ReleaseMutex();
    } 
  }

  public static void Main() 
  {
    Thread t2 = new Thread(new ThreadStart(CountUp));
    t2.Name = "t2";
    Thread t3 = new Thread(new ThreadStart(CountUp));
    t3.Name = "t3";
    t2.Start();
    t3.Start();
  }
}
t2 1
t3 2
t3 3
t3 4
t3 5
t3 6
t3 7
t3 8
t3 9
t3 10
t2 11








20.20.Mutex
20.20.1.Threading with Mutex
20.20.2.Use a Mutex to control a shared resource against two current threads
20.20.3.Use the Mutex object: WaitOne
20.20.4.Own a Mutex
20.20.5.Name a Mutex
20.20.6.How a Mutex is used to synchronize access to a protected resource