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));
Parallel. ForEach uses managed thread pool to schedule parallel actions. The number of threads is set by ThreadPool.
ForEach loop works like a Parallel. For loop. The loop partitions the source collection and schedules the work on multiple threads based on the system environment. The more processors on the system, the faster the parallel method runs.
use the Parallel. ForEach method for the simplest use case, where you just need to perform an action for each item in the collection. use the PLINQ methods when you need to do more, e.g. query the collection or to stream the data.
You don't have to do anything special, Parallel. Foreach() will wait until all its branched tasks are complete. From the calling thread you can treat it as a single synchronous statement and for instance wrap it inside a try/catch.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With