Queues And Wait Handles in C#
- by Michael Covelli
I've had the following code in my application for some years and have never seen an issue from it.
while ((PendingOrders.Count > 0) || (WaitHandle.WaitAny(CommandEventArr) != 1))
{
lock (PendingOrders)
{
if (PendingOrders.Count > 0)
{
fbo = PendingOrders.Dequeue();
}
else
{
fbo = null;
}
}
// Do Some Work if fbo is != null
}
Where CommandEventArr is made up of the NewOrderEvent (an auto reset event) and the ExitEvent (a manual reset event).
But I just realized today that its not thread safe at all. If this thread gets interrupted right after the first (PendingOrder.Count 0) check has returned false. And then the other thread both enqueues an order and sets the NewOrderEvent before I get a chance to wait on it, the body of the while loop will never run.
What's the usual pattern used with a Queue and an AutoResetEvent to fix this and do what I'm trying to do with the code above?