You say:
multiple threads are pushing data on a Queue
The Queue<T>.Enqueue
method is not thread-safe. This means that work gets done within the Enqueue
method that needs to be synchronized if multiple threads are calling it. A simple example would be updating the Count
property. It's a safe bet that somewhere in the Enqueue
method there's a line that looks something like this:
++count;
But as we all know, this isn't an atomic operation. It's really more like this (in terms of what's actually happening):
int newCount = count + 1;
count = newCount;
So say the count
is currently 5, and Thread 1 gets past int newCount = count + 1
... then Thread 1 thinks, "OK, the count is now 5, so I'll make it 6." But the very next operation that gets executed is where Thread 2 gets to int newCount = count + 1
and thinks the same thing as Thread 1 ("the count is now 6"). So two items have just been added to the queue, but the count only went from 5 to 6.
This is just a very basic example of how a non thread-safe method like Queue<T>.Enqueue
can get messed up when access is not synchronized. It doesn't specifically explain what's happening in your question; my intention is simply to point out that what you're doing is not thread-safe and will cause unexpected behavior.