[For part 1 of this series, visit here]
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.
We will dive into the code in next post.
To be continued… (in part 3)