Question

I have such piece of code:

foreach (var elem in coll.AsParallel())
{
   ... // some *local* computation
   cache.Add(elem,computation_outcome);
}

where cache is ConcurrentDictionary and Add is extension method which wraps TryAdd and throws exception on failure.

It works. The only problem is, it does not run in parallel.

Question -- what are the requirements to run loop in parallel?

I know about forcing parallel mode, but I am just asking about requirements for parallel execution.

Was it helpful?

Solution

AsParallel() is intended for LINQ queries. It will not make a normal foreach() run in parallel.

You should use something like:

Parallel.ForEach (coll, elem => 
{
   ... // some *local* computation
   cache.Add(elem,computation_outcome);
} );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top