开发者

Does Parallel.ForEach require AsParallel()

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?

Lis开发者_Python百科t<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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜