Parallel.For interruption
Asked Answered
I

2

7

Suppose you have an array of 1000 random integer numbers and you need to loop over it to find the number 68 for example.

Using the new Parallel.For on a quad core CPU would improve speed considerably, making each core to work only 250 array items.

The question is: is it possible to interrupt the Parallel.For loop when the following condition is met?

if (integerArray[i] == 68)

   break;

Thanks.

Insomniac answered 21/8, 2010 at 20:0 Comment(0)
A
9

If you want to stop after the current executing iteration are done (but iterations before the current WILL be executed - that is, the iterations with a lower index = i)

Parallel.For(0, 100, (i, s) =>
    {
        s.Break();
    });

or if you want to stop after the current and interations before this (in terms of index = i) should also stop

Parallel.For(0, 100, (i, s) =>
    {
        s.Stop();
    });

but in BOTH cases it is good practice to check if the work should be aborted if the iteration can take a while

s.ShouldExitCurrentIteration

read more here Parallel.For Method (Int32, Int32, Action(Int32, ParallelLoopState))

Abshire answered 21/8, 2010 at 20:6 Comment(1)
I mixed up some notion about Break and Stop - please reread the answer :)Abshire
R
2

It sounds to me that you should look into PLINQ (Parallel LINQ) to execute a parallel query, rather than a parallel for.
http://msdn.microsoft.com/en-us/library/dd460688.aspx

Roxana answered 21/8, 2010 at 20:5 Comment(1)
Correct for this (simple) example. But it is a more general question.Treble

© 2022 - 2024 — McMap. All rights reserved.