Reputation: 4713
Assume I have two queues holding similar message types to be sent to an endpoint. One of the queues (Queue A) has the highest priority so its messages must always be sent first. The messages in the second queue (Queue B) have a lower priority and should only be sent whilst Queue A is empty. I need to write some code that will contain these two queues and send their contents based on the above logic. I’m assuming I should do this with a new thread so that the system doesn’t hang when the queues are being emptied and whilst I am waiting for new messages to arrive. What I would like to know, is there a good pattern for this? Should I use the C# “Queue” type? Any advice on what not to do?
Upvotes: 0
Views: 158
Reputation: 109597
Use a BlockingCollection<T>
for your queue, and back it with a ConcurrentPriorityQueue<T>
You would create your ConcurrentPriorityQueue
and pass it to the BlockingCollection
constructor that accepts an IProducerConsumerCollection
Then no matter which order the producer threads add different priorities of work items, the consumer thread will remove the high priority items first.
Upvotes: 1
Reputation: 217313
The ConcurrentQueue<T> Class provides a thread-safe implementation of a queue. You could glue two instances together to form your priority queue and implement the IProducerConsumerCollection<T> Interface so it can be wrapped in a BlockingCollection<T> Class. Then any thread can add items to the queue, and one thread consumes the items using the GetConsumingEnumerable Method.
enum Priority
{
Low,
High,
}
struct Prioritized<T>
{
public Priority Priority;
public T Item;
}
class PriorityQueue<T> : IProducerConsumerCollection<Prioritized<T>>
{
private readonly ConcurrentQueue<T> low;
private readonly ConcurrentQueue<T> high;
...
}
Upvotes: 1