I need to build a blocking priority queue and my hunch is that TakeFromAny
may be the secret ingredient, however the documentation on that method is sparse. What is its purpose / appropriate use?
My requirement is that multiple threads will add to either a high priority or low priority queue. One thread will consume these two queues always taking from the high priority queue before the low priority queue.
It's quite possible that the neither the BlockingCollection
or the TakeFromAny
method will be of any use to me. If so, then a pointer in the right direction would be appreciated.
You are right. The documentation is rather sparse. However, I took a look at the implemenation via Reflector and I believe you can use the BlockingCollection.TakeFromAny
method to simulate the priority bias you desire. The reason is because the implementation uses the WaitHandle.WaitAny
method which returns the smallest index of all signaled objects. That means if you have two or more queues with items available then the queue appearing first in the array will always be chosen.
The following code should always output "high".
var low = new BlockingCollection<object> { "low" };
var high = new BlockingCollection<object> { "high" };
var array = new BlockingCollection<object>[] { high, low };
object item;
int index = BlockingCollection<object>.TakeFromAny(array, out item);
Console.WriteLine(item);
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