For Method (Int32, Int32, Action(Int32, ParallelLoopState))

Task Parallel System.Threading

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

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

Syntax

Visual Basic (Declaration)
Public Shared Function For ( _
	fromInclusive As Integer, _
	toExclusive As Integer, _
	body As Action(Of Integer, ParallelLoopState) _
) As ParallelLoopResult
C#
public static ParallelLoopResult For(
	int fromInclusive,
	int toExclusive,
	Action<int, ParallelLoopState> body
)

Parameters

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

Return Value

A ParallelLoopResult structure that contains information on what portion of the loop completed.

Remarks

The body delegate is invoked once for each value in the iteration range: [fromInclusive, toExclusive). It is provided with the following parameters: the iteration count (an Int32), and a ParallelLoopState instance that may be used to break out of the loop prematurely.

Calling ParallelLoopState.Break() informs the For operation that iterations after the current one need not execute. However, all iterations before the current one will still need to be executed if they have not already. Therefore, calling Break is similar to using a break operation within a conventional for loop in a language like C#, but it is not a perfect substitute: for example, there is no guarantee that iterations after the current one will definitely not execute.

If executing all iterations before the current one is not necessary, ParallelLoopState.Stop() should be preferred to using Break. Calling Stop informs the For loop that it may abandon all remaining iterations, regardless of whether they're for interations above or below the current, since all required work has already been completed. As with Break, however, there are no guarantees regarding which other iterations will not execute.

When a loop is ended prematurely, the ParallelLoopState that's returned will contain relevant information about the loop's completion.

Exceptions

ExceptionCondition
System..::.ArgumentNullExceptionThe exception that is thrown when the body argument is null.
System..::.AggregateExceptionThe exception that is thrown to contain an exception thrown from one of the specified delegates.

See Also