开发者

Is the BlockingCollection.TakeFromAny method suitable for building a blocking priority queue?

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 fro开发者_如何学编程m 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜