I want to write a simple producer-consumer queue, without using the built-in System.Collections.Concurrent.BlockingCollection
. Here's a quick attempt that "seems" to work. Is there anything wrong with it threading-wise, race conditions, deadlocks etc.?
class ProducerConsumerQueue<T>
{
Queue<T> Queue = new Queue<T>();
ManualResetEvent Event = new ManualResetEvent(false);
object Lock = new object();
public void Add(T t)
{
lock (Lock)
{
Queue.Enqueue(t);
}
Event.Set();
}
public bool TryTake(out T t, int timeout)
{
if (Event.WaitOne(timeout))
{
lock (Lock)
{
if (Queue.Count > 0)
{
t = Queue.Dequeue();
if (Queue.Count == 0) Event.Reset();
return true;
}
}
}
t = default(T);
return false;
}
}
Btw. the only two methods I need are Add
and TryTake
, I don't need IEnumerable
etc.