For Method (Int64, Int64, ParallelOptions, Action(Int64))

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

.NET Framework (current version)

Executes a for (For in Visual Basic) loop with 64-bit indexes 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(
	long fromInclusive,
	long toExclusive,
	ParallelOptions parallelOptions,
	Action<long> body


Type: System.Int64

The start index, inclusive.

Type: System.Int64

The end index, exclusive.

Type: System.Threading.Tasks.ParallelOptions

An object that configures the behavior of this operation.

Type: System.Action<Int64>

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.

Supports 64-bit indexes. The body delegate is invoked once for each value in the iteration range (fromInclusive, toExclusive). It is provided with the iteration count (Int64) 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 use ParallelOptions to specify a custom task scheduler:

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

class ParallelSchedulerDemo2
        // Demonstrated features:
        //		TaskScheduler
        //      BlockingCollection
        // 		Parallel.For()
        //		ParallelOptions
        // Expected results:
        // 		An iteration for each argument value (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) is executed.
        //		The TwoThreadTaskScheduler employs 2 threads on which iterations may be executed in a random order.
        //		Thus a scheduler thread may execute multiple iterations.
        // Documentation:
        // More information:
        static void Main()
            ParallelOptions options = new ParallelOptions();

            // Construct and associate a custom task scheduler
            options.TaskScheduler = new TwoThreadTaskScheduler();

                        (i, localState) =>
                            Console.WriteLine("i={0}, Task={1}, Thread={2}", i, Task.CurrentId, Thread.CurrentThread.ManagedThreadId);

            // 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("An iteration has thrown an exception. THIS WAS NOT EXPECTED.\n{0}", e);

        // This scheduler schedules all tasks on (at most) two threads
        sealed class TwoThreadTaskScheduler : TaskScheduler, IDisposable
            // The runtime decides how many tasks to create for the given set of iterations, loop options, and scheduler's max concurrency level.
            // Tasks will be queued in this collection
            private BlockingCollection<Task> _tasks = new BlockingCollection<Task>();

            // Maintain an array of threads. (Feel free to bump up _n.)
            private readonly int _n = 2;
            private Thread[] _threads;

            public TwoThreadTaskScheduler()
                _threads = new Thread[_n];

                // Create unstarted threads based on the same inline delegate
                for (int i = 0; i < _n; i++)
                    _threads[i] = new Thread(() =>
                        // The following loop blocks until items become available in the blocking collection.
                        // Then one thread is unblocked to consume that item.
                        foreach (var task in _tasks.GetConsumingEnumerable())

                    // Start each thread
                    _threads[i].IsBackground = true;

            // This method is invoked by the runtime to schedule a task
            protected override void QueueTask(Task task)

            // The runtime will probe if a task can be executed in the current thread.
            // By returning false, we direct all tasks to be queued up.
            protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
                return false;

            public override int MaximumConcurrencyLevel { get { return _n; } }

            protected override IEnumerable<Task> GetScheduledTasks()
                return _tasks.ToArray();

            // Dispose is not thread-safe with other members.
            // It may only be used when no more tasks will be queued
            // to the scheduler.  This implementation will block
            // until all previously queued tasks have completed.
            public void Dispose()
                if (_threads != null)

                    for (int i = 0; i < _n; i++)
                        _threads[i] = null;
                    _threads = null;
                    _tasks = null;


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
© 2016 Microsoft