I’ve modified Producer/Consumer example http://msdn.microsoft.com/en-us/library/yy12yx1f(v=vs.80).aspx. I don’t want Consumer to process queue “on event”. Instead i’m using infinity loop (the same to one used in Producer) and try to process all elements asap. Are there any problems with such approach? Why we need “events” between Consumer and Producer if we can use infinity loop?
// Consumer.ThreadRun
public void ThreadRun()
{
int count = 0;
while (!_syncEvents.ExitThreadEvent.WaitOne(0, false))
{
lock (((ICollection)_queue).SyncRoot)
{
while (_queue.Count > 0)
{
int item = _queue.Dequeue();
count++;
}
}
}
Console.WriteLine("Consumer Thread: consumed {0} items", count);
}
I see two potential problems with what you have
If you are using .NET 4 you might want to take a look at using BlockingCollection(T) Class which would give an even cleaner solution to all of this with less locking to boot.