question

DaveDeBenedetto-2528 avatar image
0 Votes"
DaveDeBenedetto-2528 asked DaveDeBenedetto-2528 action

ConcurrentQueue Not Always Dequeueing what was Successfully Enqueued

Hello,
I have a C# Windows service which has been running in my production environment for years.

The service has several ConcurrentQueue instances. One of these queues (queue "A") receives Enqueues from three different "producers", each one within a different thread.

A fourth thread does the Dequeuing.

I’ve made some seemingly unrelated code changes, and am perplexed by what I'm now observing: Queue "A" only correctly processes traffic from two of the three producers.

While debugging, I stopped the Enqueues from the two "working" producers, and observed the following with the "problem producer":
1. When I step through the Enqueue statement, everything looks fine: That is, the Queue.Count correctly increments, Queue.IsEmpty == false, and my data is correctly residing in a queue element.
2. However, when the fourth thread calls TryDequeue on the same queue, nothing is found. Also, Queue.IsEmpty == true, and Queue.Count == 0.
3. Repeated Enqueues cause the Queue.Count to keep increasing and my new items accumulating, as shown by the debugger.

Has anyone ever encountered this type of behavior?
Thanks in advance,
Dave

dotnet-csharp
· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.


Maybe for some reason the fourth thread and the problematic producer use different queue objects?

0 Votes 0 ·

Good suggestion - however I confirmed they're the same queue object.

0 Votes 0 ·
Viorel-1 avatar image Viorel-1 DaveDeBenedetto-2528 ·

Is the problem observed in case of various number of items already added to queue by producers?

To progress, you can try implementing a Concurrent Queue using Queue<T> class and lock(queueObject) or lock(queueObject.SyncRoot) statements. Four functions seem enough.

1 Vote 1 ·
Show more comments

1 Answer

DaveDeBenedetto-2528 avatar image
0 Votes"
DaveDeBenedetto-2528 answered Viorel-1 commented

The problem has been solved.

The cause was banal: To code a new class instantiation, I copied and modified an existing code block. But in doing so, I accidentally copied more than I meant to, inadvertently instantiating the class that creates the concurrent queues twice.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.