BlockingCollection.TakeFromAny 方法是否适合构建阻塞优先级队列? [英] Is the BlockingCollection.TakeFromAny method suitable for building a blocking priority queue?

查看:88
本文介绍了BlockingCollection.TakeFromAny 方法是否适合构建阻塞优先级队列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要构建一个阻塞优先级队列,我的预感是 TakeFromAny 可能是秘密成分,但是关于该方法的文档很少.它的目的/适当用途是什么?

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.

BlockingCollectionTakeFromAny 方法很可能对我没有任何用处.如果是这样,那么将不胜感激指向正确方向的指针.

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.

推荐答案

你说得对.文档相当稀少.但是,我通过 Reflector 查看了实现,我相信您可以使用 BlockingCollection.TakeFromAny 方法来模拟您想要的优先级偏差.原因是因为实现使用了 WaitHandle.WaitAny 方法,该方法返回所有信号对象的最小索引.这意味着如果您有两个或更多可用项目的队列,那么将始终选择数组中最先出现的队列.

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.

下面的代码应该总是输出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);

这篇关于BlockingCollection.TakeFromAny 方法是否适合构建阻塞优先级队列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆