Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Queue<T>.Dequeue returns null

I have a scenario where

  • multiple threads are pushing data on a Queue

  • only ONE thread is processing data using code below

code -

  while ( Continue )
  {
        while ( queue.Count > 0 )
        {
             MyObj o = queue.Dequeue();
             someProcess(o);
        }
        myAutoResetEvent.WaitOne();
  }

But sometimes, queue.Dequeue() returns null in the scenario above What gives ?

like image 699
Kumar Avatar asked Feb 12 '10 14:02

Kumar


People also ask

Does dequeue return anything?

Returns. The object that is removed from the beginning of the Queue.

What happens if you dequeue an empty queue?

The Dequeue() removes and returns the first element from a queue because the queue stores elements in FIFO order. Calling the Dequeue() method on an empty queue will throw the InvalidOperation exception.

What is queue in C# with example?

A Queue in C# represents a first-in, first-out (FIFO) collection of objects. An example of a queue is a line of people waiting. The Queue<T> class in the System. Collection. Generic namespace represents a queue in C#, where T specifies the type of elements in the queue.


1 Answers

You need to synchronise the access to the queue. Put lock statements around all code sections that access the queue (both reading and writing). If you access the queue simultaneously from multiple threads the internal structures may be corrupted and just about anything can happen.

like image 64
Guffa Avatar answered Sep 17 '22 15:09

Guffa