0 out of 1 rated this helpful - Rate this topic

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

Executes a for loop in which iterations may run in parallel.

Namespace:  System.Threading.Tasks
Assembly:  mscorlib (in mscorlib.dll)
public static ParallelLoopResult For(
	int fromInclusive,
	int toExclusive,
	Action<int> body
)

Parameters

fromInclusive
Type: System.Int32
The start index, inclusive.
toExclusive
Type: System.Int32
The end index, exclusive.
body
Type: System.Action<Int32>
The delegate that is invoked once per iteration.

Return Value

Type: System.Threading.Tasks.ParallelLoopResult
A ParallelLoopResult structure that contains information on what portion of the loop completed.
Exception Condition
ArgumentNullException

The exception that is thrown when the body argument is null.

AggregateException

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

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

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

.NET Framework

Supported in: 4

.NET Framework Client Profile

Supported in: 4

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Better example for maintaining the original order.
Previous code snippet by Luke Puppett is nice, but suffers with one drawback: locking. It is very resource expensive and inefficient, and should be used in cases where there is absolutely no other way to achieve thread safety. In this case you could achieve maintaining the original order and do away without locking like this:

            int from = 0;
            int to = 200000;

            int[] array = new int[to];
            Parallel.For(from, to, index =>
            {
                array[index] = index;
            });
            List<int> list = array.ToList();

In other words, declare an array with certain upper boundary, and then keep inserting desired items at their original collection's positional index: "to" variable is a count of the items in the original collection. Here is unit test for checking whether or not some items made in the list in the wrong order:


            Parallel.For(from, to, item =>
            {
                Assert.IsTrue(list.IndexOf(item) == item, string.Format("Item {0} is placed at index {1} while should have been placed at index {2}",
                     item, list.IndexOf(item), item));
            });

The Unit test as shown above validates whether or not any items occupy wrong position and it runs somewhat slow: I guess the Assert is not very fast part. The original Parallel loop is very fast even with 200K iterations.

Example and Gotcha

Note in the example how the range is inclusive and exclusive, i.e. for an entire collection of 3 items it would be For(0, 3, ...) and not For(0, 2, ...) as it would be for a normal For loop.

This example gets entities from a collection of database ids, while maintaining the original order of ids. It's a good candidate for using a Semaphore to prevent calls rinsing the database pool and I would add the code but this comment editor is so abysmal I am unable to.

var sortedByIndex = new SortedDictionary&lt;int, T&gt;();
System.Threading.Tasks.Parallel.For(0, entityIds.Count(), i =&gt;
{
var k = entityIds[i];
try
{
var entity = (new EntityGetter()).Get(k);
if (entity != null)
{
lock (sortedByIndex)
{
sortedByIndex.Add(i, entity);
}
}
}
catch (Exception e)
{
// handle
}
});