Return null using PLINQ

I have an extension method for IEnumerable, which then iterates through the collection, making it a business, and then returns a new IEnumerable.

I tried using PLINQ using .AsParallel (). ForAll (), which significantly speeds up iterations (which, of course, should do), however, when the collection returns, this collection often has several objects that are zero.

I guess this could be because he is returning the collection before all the "business" has a chance to complete? if I debug and put in a breakpoint, then there are no zeros.

Is there any waiting method for this operation that I should use?

EDIT: to be a little clearer, there is business logic in forall, changing properties, etc. it is necessary that the action is looped, and not just something.

+7
c # plinq
source share
2 answers

The answer depends on what you mean by return, because the ForAll method returns nothing. It invokes the delegate that you specify in parallel for all elements in the collection. I would suggest that your code looks like this:

 data.AsParallel().ForAll(() => /* calculate and store result somewhere */); // more code 

The ForAll method does not wait for all delegates to complete, so more code can be executed before all delegates are complete (and you also need to be careful in the store result somewhere bit, because it can be run simultaneously for several delegates!)

I think the code could be rewritten more elegantly using the Select method:

 var res = data.AsParallel().Select(() => /* calculate the result */); 

In this case, the delegate simply returns the result. The Where method collects all the results, and when you iterate over the returned IEnumerable , it ensures that all delegates complete the calculation.

+1
source share

ForAll() does not perform the merge and returns immediately. Parallel.ForEach() is probably the functionality you are looking for.

those. instead:

collection.AsParallel().ForAll( t=>t.doWork() );

something like

Parallel.ForEach(collection.AsParallel(), t=>t.doWork());

0
source share

All Articles