Reed 告诉您需要实现IProducerConsumerCollection<T> 是正确的。但是,有一个课程可以帮助您。它不是内置的,但它在 MSDN 上具有特色。只需将此ConcurrentPriorityQueue 传递给您的BlockingCollection。
我是这样使用的:
private readonly BlockingCollection<KeyValuePair<int, ICommand>> _commands
= new BlockingCollection<KeyValuePair<int, ICommand>>(
new ConcurrentPriorityQueue<int, ICommand>());
ICommand 是我项目中的一个接口。
现在这允许您添加这样的项目:
_actions.Add(new KeyValuePair<int, ICommand>(1, command1));
_actions.Add(new KeyValuePair<int, ICommand>(2, command2));
_actions.Add(new KeyValuePair<int, ICommand>(1, command3));
将优先执行具有较低整数值的项目。在上面的例子中:
command1
command3
command2
循环遍历BlockingCollection 时,您将不再获得单个元素(在我的情况下为ICommand),而是KeyValuePair。当然,这可能需要一些代码更改。一件好事是你有它原来的优先级:
foreach (var command in _queue)
{
var priority = command.Key;
var actualCommand = command.Value;
}