Yes, you must synchronize access to Queueit to make it thread safe. But you have one more problem. There is no mechanism that drives consumers to revolve around a cycle. Synchronizing access to Queueor using ConcurrentQueuewill not resolve this issue.
The easiest way to implement a producer-consumer pattern is to use a blocking queue. Fortunately, .NET 4.0 provides BlockingCollection, which, despite the name, is an implementation of a blocking queue.
public class Runner
{
private BlockingCollection<int> queue = new BlockingCollection<int>();
private Random random = new Random();
public Runner()
{
for (int i = 0; i < 2; i++)
{
var thread = new Thread(Produce);
thread.Start();
}
for (int i = 0; i < 2; i++)
{
var thread = new Thread(Consume);
thread.Start();
}
}
protected void Produce()
{
while (true)
{
int number = random.Next(0, 99);
queue.Add(number);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Produce: " + number);
}
}
protected void Consume()
{
while (true)
{
int number = queue.Take();
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Consume: " + number);
}
}
}
source
share