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

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

问题描述

为什么在使用 GetConsumableEnumerableParallel.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.ForEachBlockingCollection 有点问题,我最近发现.它可以工作,但需要一点额外的努力.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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