I wrote:
> Something like this (added lines are prepended with '+', and removed lines
> with '-')?
[snip]
Argh! I can't get it to work!
I get an exception when I try to call ProducerConsumer.Stop:
An unhandled exception of type
'System.Threading.SynchronizationLockException' occurred in
mscorlib.dll
Additional information: Object synchronization method was called from
an unsynchronized block of code.
I can't see how to get around this.
Full code:
using System;
using System.Collections;
using System.Threading;
public class Test
{
static ProducerConsumer queue = new ProducerConsumer();
static void Main()
{
new Thread(new ThreadStart(ConsumerJob)).Start();
queue.Produce(new object());
Thread.Sleep(2000);
queue.Stop();
}
static void ConsumerJob()
{
while (!queue.Stopped)
{
object o = queue.Consume();
Console.WriteLine("Consuming {0}.", o);
}
}
}
public class ProducerConsumer
{
readonly object listLock = new object();
Queue queue = new Queue();
volatile bool stopped = false;
public bool Stopped
{
get { return stopped; }
}
public void Produce(object o)
{
lock (listLock)
{
queue.Enqueue(o);
if (queue.Count==1)
{
Monitor.Pulse(listLock);
}
}
}
public object Consume()
{
lock (listLock)
{
while (queue.Count==0 && !stopped)
{
Monitor.Wait(listLock);
}
return stopped ? null : queue.Dequeue();
}
}
public void Stop()
{
stopped = true;
Monitor.Pulse(listLock);
}
}