title: C# Threading and Queues
body: <p>This isn't about the different methods I could or should be using to utilize the queues in the best manner, rather something I have seen happening that makes no sense to me.</p>
  
  <pre><code>void Runner() {
      // member variable
      queue = Queue.Synchronized(new Queue());
      while (true) {
          if (0 &lt; queue.Count) {
              queue.Dequeue();
          }
      }
  }
  </code></pre>
  
  <p>This is run in a single thread:</p>
  
  <pre><code>var t = new Thread(Runner);
  t.IsBackground = true;
  t.Start();
  </code></pre>
  
  <p>Other events are "Enqueue"ing else where. What I've seen happen is over a period of time, the Dequeue will actually throw InvalidOperationException, queue empty. This should be impossible seeing as how the count guarantees there is something there, and I'm positive that nothing else is "Dequeue"ing.</p>
  
  <p>The question(s):</p>
  
  <ol>
  <li>Is it possible that the Enqueue actually increases the count before the item is fully on the queue (whatever that means...)?</li>
  <li>Is it possible that the thread is somehow restarting (expiring, reseting...) at the Dequeue statement, but immediately after it already removed an item?</li>
  </ol>
  
  <p><strong>Edit (clarification):</strong></p>
  
  <p>These code pieces are part of a Wrapper class that implements the background helper thread. The Dequeue here is the only Dequeue, and all Enqueue/Dequeue are on the Synchronized member variable (queue).</p>