Monitor Pool : Monitor « Thread « C# / CSharp Tutorial






using System;
using System.Threading;

class MainClass
{
  private const int threads = 4;
  private const int workitems = 50;

  private static Object locker = new Object();

  static void Worker()
  {
    while( true )
    {
      lock( locker )
      {
        Monitor.Wait( locker );
      }
      System.Console.WriteLine( "{0} doing work", Thread.CurrentThread.Name );
      Thread.Sleep( 100 );
    }
  }

  [STAThread]
  static void Main(string[] args)
  {
    Thread[] t = new Thread[ threads ];

    for( int k = 0; k < threads; k++ )
    {
      t[ k ] = new Thread( new ThreadStart( Worker ) );
      t[ k ].Name = "Worker " + k;
      t[ k ].IsBackground = true;
      t[ k ].Start();
    }

    for( int i = 0; i < workitems; i ++ )
    {
      Thread.Sleep( 1000 );

      lock( locker )
      {
        Monitor.Pulse( locker );
      }
    }
  }
}








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