我已经写了一些代码来消费队列中所有的等待项。与其逐个处理这些项目,按集合方式处理所有等待的项目更有意义。
我这样声明了我的队列。
private BlockingCollection<Item> items =
new BlockingCollection<Item>(new ConcurrentQueue<Item>);
然后,在一个消费者线程上,我计划以批的方式读取这些项目,就像这样:
Item nextItem;
while (this.items.TryTake(out nextItem, -1))
{
var workToDo = new List<Item>();
workToDo.Add(nextItem);
while(this.items.TryTake(out nextItem))
{
workToDo.Add(nextItem);
}
// process workToDo, then go back to the queue.
}
这种方法缺乏使用GetConsumingEnumerable
的实用性,我不禁想知道是否有更好的方法,或者我的方法是否存在缺陷。
是否有更好的方式来批量消费 BlockingCollection<T>
?