Home > OS >  Parallel.For Conditional Statement
Parallel.For Conditional Statement

Time:05-29

I'm running a simulations in Parallel.For loops, but I need to stop then after a certain period of even if it hasn't run all the iterations.

I need to be able to do the following in Parallel.For.

for(int i = 0; i < 1_000_000 || DateTime.Now.Subtract(StartTime) >= MaxDuration; i  )
{
    // do the thing
}

CodePudding user response:

As mentioned by Heinzi in the comment, calling ParallelLoopState.Break() works after checking the condition

Parallel.For(1, 1_000_000, (i, state) =>
{
    //do the thing

    if (DateTime.Now-startTime>=maxDuration)
    {   
        state.Break();
    }

});
  • Related