Parallel.ForEach循环与BlockingCollection.GetConsumableEnumerable [英] Parallel.ForEach loop with BlockingCollection.GetConsumableEnumerable

查看:231
本文介绍了Parallel.ForEach循环与BlockingCollection.GetConsumableEnumerable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在使用GetConsumableEnumerable的同时使用OperationCancelledException,parallel.ForEach循环退出?

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有优秀的博文,如果您下载平行扩展插件项目(也可以在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆