Queues And Wait Handles in C#

Posted by Michael Covelli on Stack Overflow See other posts from Stack Overflow or by Michael Covelli
Published on 2010-04-29T21:54:09Z Indexed on 2010/04/29 21:57 UTC
Read the original article Hit count: 144

Filed under:
|
|
|
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET