17
爲什麼在使用GetConsumableEnumerable時,parallel.ForEach循環會退出OperationCancelledException?Parallel.ForEach循環與BlockingCollection.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();
}
真正令我困惑的是,爲什麼當我調用_collection.CompleteAdding()時,Parallel.ForEach拋出異常。 – Sam
@Sam:說實話,我不想說。有太多的深刻的魔力在那裏爲我有信心說正確的事情:) –
並行擴展附加的當前URL: https://code.msdn.microsoft.com/ParExtSamples 和有人已經作出一個擴展的NuGet: https://www.nuget.org/packages/MSFT.ParallelExtensionsExtras/ – Reyhn