Export (0) Print
Expand All

Parallel.For Method (Int32, Int32, ParallelOptions, Action<Int32>)

Executes a for (For in Visual Basic) loop in which iterations may run in parallel and loop options can be configured.

Namespace:  System.Threading.Tasks
Assembly:  mscorlib (in mscorlib.dll)

public static ParallelLoopResult For(
	int fromInclusive,
	int toExclusive,
	ParallelOptions parallelOptions,
	Action<int> body
)

Parameters

fromInclusive
Type: System.Int32

The start index, inclusive.

toExclusive
Type: System.Int32

The end index, exclusive.

parallelOptions
Type: System.Threading.Tasks.ParallelOptions

An object that configures the behavior of this operation.

body
Type: System.Action<Int32>

The delegate that is invoked once per iteration.

Return Value

Type: System.Threading.Tasks.ParallelLoopResult
A structure that contains information about which portion of the loop completed.

ExceptionCondition
OperationCanceledException

The CancellationToken in the parallelOptions argument is canceled.

ArgumentNullException

The body argument is null.

-or-

The parallelOptions argument is null.

AggregateException

The exception that contains all the individual exceptions thrown on all threads.

ObjectDisposedException

The CancellationTokenSource associated with the CancellationToken in the parallelOptions has been disposed.

The body delegate is invoked once for each value in the iteration range (fromInclusive, toExclusive). It is provided with the iteration count (Int32) as a parameter.

If fromInclusive is greater than or equal to toExclusive, then the method returns immediately without performing any iterations.

The following example shows how to cancel a parallel loop:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

class ParallelForCancellation
{
    // Demonstrated features: 
    //		CancellationTokenSource 
    // 		Parallel.For() 
    //		ParallelOptions 
    //		ParallelLoopResult 
    // Expected results: 
    // 		An iteration for each argument value (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) is executed. 
    //		The order of execution of the iterations is undefined. 
    //		The iteration when i=2 cancels the loop. 
    //		Some iterations may bail out or not start at all; because they are temporally executed in unpredictable order,  
    //          it is impossible to say which will start/complete and which won't. 
    //		At the end, an OperationCancelledException is surfaced. 
    // Documentation: 
    //		http://msdn.microsoft.com/en-us/library/system.threading.cancellationtokensource(VS.100).aspx 
    static void CancelDemo()
    {
        CancellationTokenSource cancellationSource = new CancellationTokenSource();
        ParallelOptions options = new ParallelOptions();
        options.CancellationToken = cancellationSource.Token;

        try
        {
            ParallelLoopResult loopResult = Parallel.For(
                    0,
                    10,
                    options,
                    (i, loopState) =>
                    {
                        Console.WriteLine("Start Thread={0}, i={1}", Thread.CurrentThread.ManagedThreadId, i);

                        // Simulate a cancellation of the loop when i=2 
                        if (i == 2)
                        {
                            cancellationSource.Cancel();
                        }

                        // Simulates a long execution 
                        for (int j = 0; j < 10; j++)
                        {
                            Thread.Sleep(1 * 200);

                            // check to see whether or not to continue 
                            if (loopState.ShouldExitCurrentIteration) return;
                        }

                        Console.WriteLine("Finish Thread={0}, i={1}", Thread.CurrentThread.ManagedThreadId, i);
                    }
                );

            if (loopResult.IsCompleted)
            {
                Console.WriteLine("All iterations completed successfully. THIS WAS NOT EXPECTED.");
            }
        }
        // No exception is expected in this example, but if one is still thrown from a task, 
        // it will be wrapped in AggregateException and propagated to the main thread. 
        catch (AggregateException e)
        {
            Console.WriteLine("Parallel.For has thrown an AggregateException. THIS WAS NOT EXPECTED.\n{0}", e);
        }
        // Catching the cancellation exception 
        catch (OperationCanceledException e)
        {
            Console.WriteLine("An iteration has triggered a cancellation. THIS WAS EXPECTED.\n{0}", e.ToString());
        }
    }
}

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4

.NET Framework Client Profile

Supported in: 4

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1

Windows Phone 8.1, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft