BlockingCollection.TakeFromAny 方法是否适合构建阻塞优先级队列?

发布于 2024-09-19 15:29:29 字数 421 浏览 2 评论 0原文

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

我的要求是多个线程将添加到高优先级或低优先级队列中。一个线程将消耗这两个队列,并且始终先从高优先级队列获取,然后再从低优先级队列获取。

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

策马西风 2024-09-26 15:29:29

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

以下代码应始终输出“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);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文