Parallel .Foreach C # Pause and Stop Function?

What would be the most efficient way to pause and stop (until it is completed) parallel.foreach?

Parallel.ForEach(list, (item) =>
{
    doStuff(item);
});
+5
source share
2 answers

Damien_The_Unbeliver , , - . , , break for foreach, , ParallelLoopState . ParallelLoopState , , , Stop() Break().

Stop() , , Stop() , , , , .

Break() , Stop(), IEnumerable, , Break() on. , , , .

ParallelLoopResult, foreach, , foreach , Break(), .

Parallel.ForEach(list, (item, loopState) =>
    {
        bool endEarly = doStuff(item);
        if(endEarly)
        {
            loopState.Break();
        }
    }
    );
//Equivalent to the following non parallel version, except that if doStuff ends early
//    it may or may not processed some items in the list after the break.
foreach(var item in list)
{
    bool endEarly = doStuff(item);
    if(endEarly)
    {
        break;
    }
}

static bool[] list = new int[]{false, false, true, false, true, false};

long LowestElementTrue()
{
    ParallelLoopResult result = Parallel.ForEach(list, (element, loopState) =>
    {
        if(element)
            loopState.Break();
    }
    if(result.LowestBreakIteration.IsNull)
        return -1;
    else
        return result.LowestBreakIteration.Value;
}   

, , 2 .

, , 0-2, 3-5.

Thread 1:                Thread 2
0, False, continue next  3, False, continue next
1, False, continue next  4, True, Break
2, True, Break           5, Don't process Broke

Break 2, ParallelLoopResult.LowestBreakIteration 2 , , , 2.

, Stop.

static bool[] list = new int[]{false, false, true,  false, true, false};

long FirstElementFoundTrue()
{
    long currentIndex = -1;
    ParallelLoopResult result = Parallel.ForEach(list, (element, loopState, index) =>
    {
        if(element)
        {
             loopState.Stop();

             //index is a 64 bit number, to make it a atomic write
             // on 32 bit machines you must either:
             //   1. Target 64 bit only and not allow 32 bit machines.
             //   2. Cast the number to 32 bit.
             //   3. Use one of the Interlocked methods.
             Interlocked.Exchange (ref currentIndex , index);
        }
    }
    return currentIndex;
}   

, , 2 4 .

, , 0-2, 3-5.

Thread 1:                 Thread 2
0, False, continue next    3, False, continue next
1, False, continue next    4, True, Stop
2, Don't process, Stopped  5, Don't process, Stopped

4 . , 0-2 3-5.

Thread 1:                   Thread 2
0, False, continue next     1, False, continue next
2, True, Stop               3, False, continue next
4, Don't process, Stopped   5, Don't process, Stopped

2 4.

+11

Parallel.ForEach, , ParallelOptions CancellationToken .

. .

, , . , Barrier ( , , A, B), , Parallel.ForEach, , .

+2

All Articles