Does Parallel.ForEach require AsParallel()

2019-04-03 13:03发布

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条回答
叼着烟拽天下
2楼-- · 2019-04-03 13:36

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));
查看更多
登录 后发表回答