title: Queues And Wait Handles in C#
body: <p>I've had the following code in my application for some years and have never seen an issue from it.</p>
  
  <pre><code>while ((PendingOrders.Count &gt; 0) || (WaitHandle.WaitAny(CommandEventArr) != 1))
  {
      lock (PendingOrders)
      {
         if (PendingOrders.Count &gt; 0)
         {
             fbo = PendingOrders.Dequeue();
         }
         else
         {
             fbo = null;
         }
      }
  
      // Do Some Work if fbo is != null
  }
  </code></pre>
  
  <p>Where CommandEventArr is made up of the NewOrderEvent (an auto reset event) and the ExitEvent (a manual reset event).</p>
  
  <p>But I'm not sure if this is thread safe (assuming N producer threads that all lock the queue before enqueing and one consumer thread that runs the code above).  Also, we can assume that the Queue.Count property just returns one instance Int32 value from the Queue class (without volatile or interlocked or a lock, etc.).</p>
  
  <p>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?</p>
  
  <p>(Edited to change the question slightly after it was correctly pointed out that Queue.Count could do anything and its implementation specific).</p>