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

.NET Framework (current version)

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


Type: System.Int32

The start index, inclusive.

Type: System.Int32

The end index, exclusive.

Type: System.Threading.Tasks.ParallelOptions

An object that configures the behavior of this operation.

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.

Exception Condition

The CancellationToken in the parallelOptions argument is canceled.


The body argument is null.


The parallelOptions argument is null.


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


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:
    static void CancelDemo()
        CancellationTokenSource cancellationSource = new CancellationTokenSource();
        ParallelOptions options = new ParallelOptions();
        options.CancellationToken = cancellationSource.Token;

            ParallelLoopResult loopResult = Parallel.For(
                    (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)

                        // 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());

Universal Windows Platform
Available since 8
.NET Framework
Available since 4.0
Portable Class Library
Supported in: portable .NET platforms
Windows Phone
Available since 8.1
Return to top