是否Parallel.ForEach需要进行AsParallel() [英] Does Parallel.ForEach require AsParallel()

查看:559
本文介绍了是否Parallel.ForEach需要进行AsParallel()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ParallelEnumerable 有一个静态成员进行AsParallel 。如果我有一个的IEnumerable< T> ,并希望使用 Parallel.ForEach 这是否意味着我应始终使用进行AsParallel

例如。 都是这些正确的(所有其他条件相同的)?

没有进行AsParallel

 名单,其中,串>名单=新的名单,其中,串>();
Parallel.ForEach&其中;串GT;(GetFileList()如(文件=> reader.Match(文件))中,f => list.Add(六));
 

进行AsParallel

 名单,其中,串>名单=新的名单,其中,串>();
Parallel.ForEach&其中;串GT;(GetFileList()如(文件=> reader.Match(文件))进行AsParallel()中,f => list.Add(六));
 

解决方案

这要看什么被称为,它们是不同的问题。

.AsParallel()并行化的枚举任务没有了代表团一行。

Parallel.ForEach 并行化的循环,将任务分配给工作线程的每个元素。

所以,除非成为并行源枚举的收益(如 reader.Match(文件)是昂贵的),他们是平等的。为了你的最后一个问题,,两者也是正确的。

此外,还有另外一个结构,你可能想看看这缩短了一点,仍然得到PLINQ的最大好处:

  GetFileList(),其中(文件=> reader.Match(文件))。的ForAll(F => list.Add(F));
 

ParallelEnumerable has a static member AsParallel. If I have an IEnumerable<T> and want to use Parallel.ForEach does that imply that I should always be using AsParallel?

e.g. Are both of these correct (everything else being equal)?

without AsParallel:

List<string> list = new List<string>();
Parallel.ForEach<string>(GetFileList().Where(file => reader.Match(file)), f => list.Add(f));

or with AsParallel?

List<string> list = new List<string>();
Parallel.ForEach<string>(GetFileList().Where(file => reader.Match(file)).AsParallel(), f => list.Add(f));

解决方案

It depends on what's being called, they are separate issues.

.AsParallel() Parallelizes the enumeration not the delegation of tasks.

Parallel.ForEach Parallelized the loop, assigning tasks to worker threads for each element.

So unless your source enumeration gains from becoming parallel (e.g. reader.Match(file) is expensive), they are equal. To your last question, yes, both are also correct.

Also, there's one other construct you may want to look at that shortens it a bit, still getting maximum benefit of PLINQ:

GetFileList().Where(file => reader.Match(file)).ForAll(f => list.Add(f));

这篇关于是否Parallel.ForEach需要进行AsParallel()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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