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 ?
Returns. The object that is removed from the beginning of the 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With