dmg
dmg

Reputation: 605

Whats the best way to terminate a Parallel.ForEach loop from the local init lambda?

In my Parallel.ForEach loop i have some objects that I need to initialize in the "local init" lambda. If one of these objects fails to initialize, I would like to terminate the entire parallel loop. What is the best way to do this?

Parallel.ForEach(collection,
   () => //local init
   {
      var localObjects= CreateObjects();
      foreach (var obj in localObjects)
         if (!obj.Initialize())
            // want to terminate the entire parallel loop here!!
      return localObjects;
   }
   (element, loopState, localObjects) => // loop body
   {
      // some code here
   },
   localObjects => // local finally
   {
      foreach (var obj in localObjects)
         obj.Terminate();
   });

Upvotes: 0

Views: 599

Answers (2)

MoonKnight
MoonKnight

Reputation: 23833

The best way to do this (with out seeing any code), would be to check if the object you attempted to initialise is null, if it is, break().

I hope this helps.

Edit. Following some comments, stop() might be the better option in this case.

Upvotes: 1

J. Steen
J. Steen

Reputation: 15578

Perhaps something like this.

Parallel.ForEach(collection,
   () => //local init
   {
      var localObjects= CreateObjects();
      foreach (var obj in localObjects)
         if (!obj.Initialize())
            return null; // returning null as a "flag" for the loop
                         // body block to use
      return localObjects;
   },
   (element, loopState, localObjects) => // loop body
   {
      if (state.IsStopped || localObjects == null)
      {
         // will signal to stop at earliest convenience
         loopState.Stop();

         // will make sure nothing is done this iteration
         return null;
      }

      // some code here
   },
   localObjects => // local finally
   {
      foreach (var obj in localObjects)
         obj.Terminate();
   });

Note that this will mean that localObjects in the finally block will be null as well, and nothing will be Terminate()d.

Upvotes: 3

Related Questions