简体   繁体   English

带有 BlockingCollection.GetConsumableEnumerable 的 Parallel.ForEach 循环

[英]Parallel.ForEach loop with BlockingCollection.GetConsumableEnumerable

Why Parallel.ForEach loop exits with OperationCancelledException , while using GetConsumableEnumerable ?为什么Parallel.ForEach循环在使用GetConsumableEnumerable时以OperationCancelledException退出?

//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();
}

Using Parallel.ForEach with BlockingCollection is somewhat problematic, as I found out recently.正如我最近发现的那样,将Parallel.ForEachBlockingCollection一起使用有些问题。 It can be made to work, but it needs a little extra effort.它可以工作,但需要一点额外的努力。

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. Stephen Toub 有一篇很棒的博客文章,如果您下载“Parallel Extension Extras”项目( 也可在 NuGet 上找到),您会发现一些代码可以帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM