title: Multithreaded .NET queue problems
body: <p>I'm have a wierd error in my code. It's extremely rare (happens once every few weeks maybe), but it's there and I'm not sure why.</p>
  
  <p>We have 2 threads running, 1 thread gets networked messages and adds them to a Queue like this:</p>
  
  <pre><code>DataMessages.Enqueue(new DataMessage(client, msg));
  </code></pre>
  
  <p>Another thread takes messages off this queue and handles them, like this:</p>
  
  <pre><code>while (NetworkingClient.DataMessages.Count &gt; 0)
  {
      DataMessage message = NetworkingClient.DataMessages.Dequeue();
  
      switch (message.messageType)
      {
         ...
      }
  }
  </code></pre>
  
  <p>However once every so often I get a NullReferenceException on the line <code>switch (message.messageType)</code> and I can see in the debugger that message is null.</p>
  
  <p>It is not possible that a null value was put onto the queue (see the first bit of code), and these are the only 2 things that use the queue.</p>
  
  <p>Is Queue not thread-safe, could it be that I'm dequeuing at the exact moment that the other thread is enqueuing and this causes the glitch?</p>