I used this code as a queue that locks on Dequeue()until an item is queued. I have used this code for several years in several projects, no problem ... so far. I see a dead end in some code that I am writing now, and, exploring the problem, my “eye of suspicion” stopped there BlockingQueue<T>. I can’t prove it, so I thought I would ask some people smarter than me to review it for potential problems. Can you guys see anything that could cause a dead end in this code?
public class BlockingQueue<T>
{
private readonly Queue<T> _queue;
private readonly ManualResetEvent _event;
public BlockingQueue()
{
_queue = new Queue<T>();
_event = new ManualResetEvent(false);
}
public int Size
{
get
{
int count;
lock (_queue)
{
count = _queue.Count;
}
return count;
}
}
public void Enqueue(T element)
{
lock (_queue)
{
_queue.Enqueue(element);
_event.Set();
}
}
public T Dequeue()
{
T element;
while (true)
{
if (Size == 0)
{
_event.Reset();
_event.WaitOne();
}
lock (_queue)
{
if (_queue.Count == 0) continue;
element = _queue.Dequeue();
break;
}
}
return element;
}
public void Clear()
{
lock (_queue)
{
_queue.Clear();
}
}
}
source
share