Parallel.For Method (Int32, Int32, Action<Int32>)
Executes a for loop in which iterations may run in parallel.
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.ParallelLoopResultA 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. |
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.
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.
- 11/11/2011
- Sergey The Russian
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<int, T>();
System.Threading.Tasks.Parallel.For(0, entityIds.Count(), i =>
{
var k = entityIds[i];
try
{
var entity = (new EntityGetter()).Get(k);
if (entity != null)
{
lock (sortedByIndex)
{
sortedByIndex.Add(i, entity);
}
}
}
catch (Exception e)
{
// handle
}
});
- 9/3/2010
- LukePuplett
- 9/6/2010
- LukePuplett