Use Monitor to control more than one Threads : Monitor « Thread « C# / CSharp Tutorial






using System;
using System.Threading;

class MyClass
{
  private int counter;

  public void DoSomeWork()
  {
    lock(this)
    {
      counter++;
      // Do the work.
      for(int i = 0; i < 5; i++)
      {
        Console.WriteLine("counter: {0}, i: {1}, current thread: {2}",
          counter, i, Thread.CurrentThread.Name);
        Thread.Sleep(1000);
      }
    }
  }
}

public class MainClass
{
  public static int Main(string[] args)
  {
    MyClass w = new MyClass();

    Thread workerThreadA = new Thread(new ThreadStart(w.DoSomeWork));
    workerThreadA.Name = "A";
    Thread workerThreadB = new Thread(new ThreadStart(w.DoSomeWork));
    workerThreadB.Name = "B";
    Thread workerThreadC = new Thread(new ThreadStart(w.DoSomeWork));
    workerThreadC.Name = "C";

    // Now start each one.
    workerThreadA.Start();
    workerThreadB.Start();
    workerThreadC.Start();
    
    return 0;
  }
}
counter: 1, i: 0, current thread: A
counter: 1, i: 1, current thread: A
counter: 1, i: 2, current thread: A
counter: 1, i: 3, current thread: A
counter: 1, i: 4, current thread: A
counter: 2, i: 0, current thread: B
counter: 2, i: 1, current thread: B
counter: 2, i: 2, current thread: B
counter: 2, i: 3, current thread: B
counter: 2, i: 4, current thread: B
counter: 3, i: 0, current thread: C
counter: 3, i: 1, current thread: C
counter: 3, i: 2, current thread: C
counter: 3, i: 3, current thread: C
counter: 3, i: 4, current thread: C








20.19.Monitor
20.19.1.Use Wait() and Pulse() to create a ticking clock
20.19.2.Use Monitors
20.19.3.Monitor: Enter and Exit
20.19.4.Monitor: try to enter
20.19.5.Coordinate two threads using Monitor
20.19.6.Use Monitor to control more than one Threads
20.19.7.Increment Monitor
20.19.8.Monitor Pool
20.19.9.Throw exception between Monitor.Enter and Montor.Exit
20.19.10.Using A Monitor
20.19.11.Use lock and Monitor to coordinate Producer and Consumer