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.
We have 2 threads running, 1 thread gets networked messages and adds them to a Queue like this:
DataMessages.Enqueue(new DataMessage(client, msg));
Another thread takes messages off this queue and handles them, like this:
while (NetworkingClient.DataMessages.Count > 0)
{
DataMessage message = NetworkingClient.DataMessages.Dequeue();
switch (message.messageType)
{
...
}
}
However once every so often I get a NullReferenceException on the line switch (message.messageType)
and I can see in the debugger that message is null.
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.
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?