How do I collect return values from Parallel.ForEach?
Your may consider using AsParallel
extension method of IEnumerable
, it will take care of the concurrency for you and collect the results.
words.AsParallel().Select(AddB).ToArray()
Synchronisation (e.g. locks or concurrent collections that use locks) are usually bottleneck of concurrent algorithms. The best is to avoid synchronisation as much as possible. I am guessing that AsParallel
uses something smarter like putting all the items produced on single thread into a local non-concurrent collection and then combining these at the end.
You've discarded it in here.
ParallelLoopResult result = Parallel.ForEach(words, word => AddB(word));
You probably want something like,
ParallelLoopResult result = Parallel.ForEach(words, word =>
{
string result = AddB(word);
// do something with result
});
If you want some sort of collection at the end of this, consider using one of the collections under System.Collections.Concurrent
, like ConcurrentBag
ConcurrentBag<string> resultCollection = new ConcurrentBag<string>();
ParallelLoopResult result = Parallel.ForEach(words, word =>
{
resultCollection.Add(AddB(word));
});
// Do something with the result