using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace MonitorExample { class Program { static Queue queue; static void Read() { lock (queue) { while (true) { if (queue.Count == 0) { Monitor.Pulse(queue); Monitor.Wait(queue); } else { Console.WriteLine("Removed {0}", queue.Dequeue()); Thread.Sleep(300); //as if something time consuming was happening } } } } static void Write() { lock (queue) { for (int i = 0; i < 100; i++) { queue.Enqueue(i); Console.WriteLine("Added {0}", i); Random r = new Random(); Monitor.Pulse(queue); if (r.Next() % 2 == 0) { Monitor.Wait(queue); } } } } static void Main(string[] args) { queue = new Queue(); Thread one = new Thread(Read); Thread two = new Thread(Write); two.Start(); one.Start(); } } }