Using A Monitor : Monitor « Thread « C# / CSharp Tutorial






using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

class Tester
{
    static long counter = 0;
    //new Tester();
    static void Main()
    {
        Thread[] myThreads = {
               new Thread( new ThreadStart(Decrementer) ),
               new Thread( new ThreadStart(Incrementer) )              
            };
        int ctr = 1;
        foreach (Thread myThread in myThreads)
        {
            myThread.IsBackground = true;
            myThread.Start();
            myThread.Name = "Thread" + ctr.ToString();
            ctr++;
            Console.WriteLine("Started thread {0}", myThread.Name);
            Thread.Sleep(50);
        }
        foreach (Thread myThread in myThreads)
        {
            myThread.Join();
        }
    }
    static void Decrementer()
    {
        try
        {
            Monitor.Enter(counter);
            if (counter < 10)
            {
                Console.WriteLine(Thread.CurrentThread.Name);
                Console.WriteLine(counter);
                Monitor.Wait(counter);
            }
            while (counter > 0)
            {
                long temp = counter;
                temp--;
                Thread.Sleep(1);
                counter = temp;
                Console.WriteLine(Thread.CurrentThread.Name);
                Console.WriteLine(counter);
            }
        }
        finally
        {
            Monitor.Exit(counter);
        }
    }

    static void Incrementer()
    {
        try
        {
            Monitor.Enter(counter);
            while (counter < 10)
            {
                long temp = counter;
                temp++;
                Thread.Sleep(1);
                counter = temp;
                Console.WriteLine(Thread.CurrentThread.Name);
                Console.WriteLine(counter);
            }
            Monitor.Pulse(counter);
        }
        finally
        {
            Monitor.Exit(counter);
        }
    }
}








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