问题描述
为什么在使用 GetConsumableEnumerable
时 Parallel.ForEach
循环以 OperationCancelledException
退出?
Why Parallel.ForEach
loop exits with OperationCancelledException
, while using GetConsumableEnumerable
?
//outside the function
static BlockingCollection<double> _collection = new BlockingCollection<double>();
var t = Task.Factory.StartNew(Producer);
Parallel.ForEach(_collection.GetConsumingEnumerable(),
item => Console.WriteLine("Processed {0}", item));
Console.WriteLine("FINISHED processing");
public static void Producer()
{
var data = Enumerable.Range(1, 1000);
foreach (var i in data)
{
_collection.Add(i);
Console.WriteLine("Added {0}",i);
}
Console.WriteLine("Finished adding");
_collection.CompleteAdding();
}
推荐答案
使用 Parallel.ForEach
和 BlockingCollection
有点问题,我最近发现.它可以工作,但需要一点额外的努力.
Using Parallel.ForEach
with BlockingCollection
is somewhat problematic, as I found out recently. It can be made to work, but it needs a little extra effort.
Stephen Toub 有一篇优秀的博客文章,如果您下载 Parallel Extension Extras" 项目(也可在 NuGet 上找到)您会发现一些代码可以帮助您.
Stephen Toub has an excellent blog post on it, and if you download the "Parallel Extension Extras" project (also available on NuGet) you'll find some code ready to help you.
这篇关于Parallel.ForEach 循环与 BlockingCollection.GetConsumableEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!