Omer Keidar Omer Keidar - 2 months ago 9
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?

----------------------------------EDIT-----------------------------

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

if(BytesToRead>0)
{
byte[] data=new byte[BytesToRead];
Read(data,0,data.length)
MyClass c=new MyClass(){m_data=data, m_tod=DateTime.Now};
_dataQueue.Enqueue(c);
}


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

lock(_sync)
{
var item=_dataQueue.dequeue();
}


when i dequeue i get null. as you can see i use
DateTime.Now
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

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:

//_dataQueue.Enqueue(c);
lock(_sync)
{
   _dataQueue.Enqueue(c);
}