Menu

C#|.NET : Generic Concurrent Queue (2/6)

This queue is similar to some classes introduced in Concurrent namespace in .NET 4 onwards. My custom implementation of consumer/producer queue works with most of the versions of .NET (including Silverlight and WP7.X) because it uses basic wait and lock mechanism. I designed and used this in my app.

Concurrent queue is accessible on multiple threads asynchronously. To ensure only and only one operation is performed at a given time on the queue, I implemented basic semaphore solution. In this mechanism, a mutually exclusive object (Mutex) is locked, waited upon, and pulsed during a cycle of exclusive operation on queue. .NET provides lock keyword to ensure mutual exclusion and Monitor class for waiting and signaling.

The implementation is as follows; a background thread keeps waiting, with Monitor.Wait(), for new task to be added to the queue. When a new task-enqueue request arrives, the class locks the queue and enqueues the task. When task is enqueued, calling thread is freed and the waiting background thread is informed about the availability of the new task. As soon as the background thread gets a signal, it acquires a lock on the queue and dequeues the task for processing. Soon after dequeuing, the lock on queue is released. The background thread continues processing the task. After processing is complete the control loops back to dequeue next task if available or continue waiting.

Hey Sanjay thanks for your reply. While going through this article I has a doubt in my mind. The doubt is will the Queue be always empty since a thread will enqueue an item in the queue another threading is waiting to dequeue the same item.A background thread keeps waiting, with Monitor.Wait(), for new task to be added to the queue. When a new task-enqueue request arrives, the class locks the queue and enqueues the task. When task is enqueued, calling thread is freed and the waiting background thread is informed about the availability of the new task. As soon as the background thread gets a signal, it acquires a lock on the queue and dequeues the task for processing. In such a case there will be no chance of the item to get piled up in the queue. Operation will happen only on current item unit it is removed.
Can you please clear my doubt on this Sanjay. Let me know if I’m going wrong somehwere.