Omer Keidar Omer Keidar - 1 year ago 86
C# Question

c# multi-threaded queue items are null

My application is a multi-threaded application. I use threads and Tasks to enqueue and dequeue items from ~4 queues using locks.
Sometimes, when i dequeue, the item is null and when i look inside the queue i can see some other items are null too (e.g the 5th item is null).
whenever i enqueue i always create a new item, so it being null is impossible. at first i thought that another thread is messing with my items. but when i saw that the 5th item was null too,while the 3rd, 4th and 2nd wasn't i realized that its impossible because you cant touch the 5th item before dequeueing the previous items.
i cannot share my code.
is someone familiar with that kind of situation?
what could be the cause?


the class that enqueues the queue inherits from serial port and enqueues like this:

byte[] data=new byte[BytesToRead];
MyClass c=new MyClass(){m_data=data, m_tod=DateTime.Now};

and the classes that dequeues vary but the idea is similar:

var item=_dataQueue.dequeue();

when i dequeue i get null. as you can see i use
so its really wierd that it goes null. I mean if a thread uses this so the item shouldnt be there right?
each class that uses the queue has a copy of it. and inside every class there are about 3 threads that uses the queue

Answer Source

that its impossible because you cant touch the 5th item before dequeueing the previous items.

That reasoning does not hold when a collection that is not thread-safe is used from multiple threads. A race-condition can lead to all sorts of symptoms.

So best thing is to check your locking. If possible, post a mock-up of the code.

After the ----Edit---- :

Your are not locking around the Enqueue. The basic fix:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download