Does Parallel.ForEach require AsParallel()

那年仲夏 提交于 2020-01-01 08:02:57

问题


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));

回答1:


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));


来源:https://stackoverflow.com/questions/2270097/does-parallel-foreach-require-asparallel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!