Parallel.ForEach Method
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Executes a foreach
(For Each
in Visual Basic) operation in which iterations may run in parallel.
Overloads
ForEach<TSource,TLocal>(IEnumerable<TSource>, ParallelOptions, Func<TLocal>, Func<TSource,ParallelLoopState,TLocal,TLocal>, Action<TLocal>) |
Executes a |
ForEach<TSource,TLocal>(IEnumerable<TSource>, ParallelOptions, Func<TLocal>, Func<TSource,ParallelLoopState,Int64,TLocal,TLocal>, Action<TLocal>) |
Executes a |
ForEach<TSource,TLocal>(Partitioner<TSource>, ParallelOptions, Func<TLocal>, Func<TSource,ParallelLoopState,TLocal,TLocal>, Action<TLocal>) |
Executes a |
ForEach<TSource,TLocal>(OrderablePartitioner<TSource>, ParallelOptions, Func<TLocal>, Func<TSource,ParallelLoopState,Int64,TLocal,TLocal>, Action<TLocal>) |
Executes a |
ForEach<TSource,TLocal>(IEnumerable<TSource>, Func<TLocal>, Func<TSource,ParallelLoopState,TLocal,TLocal>, Action<TLocal>) |
Executes a |
ForEach<TSource,TLocal>(IEnumerable<TSource>, Func<TLocal>, Func<TSource,ParallelLoopState,Int64,TLocal,TLocal>, Action<TLocal>) |
Executes a |
ForEach<TSource,TLocal>(Partitioner<TSource>, Func<TLocal>, Func<TSource,ParallelLoopState,TLocal,TLocal>, Action<TLocal>) |
Executes a |
ForEach<TSource,TLocal>(OrderablePartitioner<TSource>, Func<TLocal>, Func<TSource,ParallelLoopState,Int64,TLocal,TLocal>, Action<TLocal>) |
Executes a |
ForEach<TSource>(IEnumerable<TSource>, ParallelOptions, Action<TSource>) |
Executes a |
ForEach<TSource>(IEnumerable<TSource>, ParallelOptions, Action<TSource,ParallelLoopState>) |
Executes a |
ForEach<TSource>(OrderablePartitioner<TSource>, ParallelOptions, Action<TSource,ParallelLoopState,Int64>) |
Executes a |
ForEach<TSource>(Partitioner<TSource>, ParallelOptions, Action<TSource>) |
Executes a |
ForEach<TSource>(IEnumerable<TSource>, ParallelOptions, Action<TSource,ParallelLoopState,Int64>) |
Executes a |
ForEach<TSource>(Partitioner<TSource>, Action<TSource,ParallelLoopState>) |
Executes a |
ForEach<TSource>(Partitioner<TSource>, Action<TSource>) |
Executes a |
ForEach<TSource>(IEnumerable<TSource>, Action<TSource,ParallelLoopState,Int64>) |
Executes a |
ForEach<TSource>(OrderablePartitioner<TSource>, Action<TSource,ParallelLoopState,Int64>) |
Executes a |
ForEach<TSource>(IEnumerable<TSource>, Action<TSource>) |
Executes a |
ForEach<TSource>(Partitioner<TSource>, ParallelOptions, Action<TSource,ParallelLoopState>) |
Executes a |
ForEach<TSource>(IEnumerable<TSource>, Action<TSource,ParallelLoopState>) |
Executes a |
ForEach<TSource,TLocal>(IEnumerable<TSource>, ParallelOptions, Func<TLocal>, Func<TSource,ParallelLoopState,TLocal,TLocal>, Action<TLocal>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation with thread-local data on an IEnumerable in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated.
public:
generic <typename TSource, typename TLocal>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Generic::IEnumerable<TSource> ^ source, System::Threading::Tasks::ParallelOptions ^ parallelOptions, Func<TLocal> ^ localInit, Func<TSource, System::Threading::Tasks::ParallelLoopState ^, TLocal, TLocal> ^ body, Action<TLocal> ^ localFinally);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource,TLocal> (System.Collections.Generic.IEnumerable<TSource> source, System.Threading.Tasks.ParallelOptions parallelOptions, Func<TLocal> localInit, Func<TSource,System.Threading.Tasks.ParallelLoopState,TLocal,TLocal> body, Action<TLocal> localFinally);
static member ForEach : seq<'Source> * System.Threading.Tasks.ParallelOptions * Func<'Local> * Func<'Source, System.Threading.Tasks.ParallelLoopState, 'Local, 'Local> * Action<'Local> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource, TLocal) (source As IEnumerable(Of TSource), parallelOptions As ParallelOptions, localInit As Func(Of TLocal), body As Func(Of TSource, ParallelLoopState, TLocal, TLocal), localFinally As Action(Of TLocal)) As ParallelLoopResult
Type Parameters
- TSource
The type of the data in the source.
- TLocal
The type of the thread-local data.
Parameters
- source
- IEnumerable<TSource>
An enumerable data source.
- parallelOptions
- ParallelOptions
An object that configures the behavior of this operation.
- localInit
- Func<TLocal>
The function delegate that returns the initial state of the local data for each task.
- body
- Func<TSource,ParallelLoopState,TLocal,TLocal>
The delegate that is invoked once per iteration.
- localFinally
- Action<TLocal>
The delegate that performs a final action on the local state of each task.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The source
argument is null
.
-or-
The parallelOptions
argument is null
.
-or-
The body
argument is null
.
-or-
The localInit
argument is null
.
-or-
The localFinally
argument is null
.
The CancellationToken in the parallelOptions
argument is canceled.
The CancellationTokenSource associated with the CancellationToken in the parallelOptions
has been disposed.
The exception that contains all the individual exceptions thrown on all threads.
Remarks
The body
delegate is invoked once for each element in the source
enumerable. It is provided with the following parameters: the current element, a ParallelLoopState instance that may be used to break out of the loop prematurely, and some local state that may be shared amongst iterations that execute on the same thread.
The localInit
delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first body
invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the localFinally
delegate. The localFinally
delegate is invoked once per thread to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables.
The Parallel.ForEach method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying TaskScheduler object the chance to add, change, or remove threads that service the loop.
See also
Applies to
ForEach<TSource,TLocal>(IEnumerable<TSource>, ParallelOptions, Func<TLocal>, Func<TSource,ParallelLoopState,Int64,TLocal,TLocal>, Action<TLocal>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation with thread-local data and 64-bit indexes on an IEnumerable in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated.
public:
generic <typename TSource, typename TLocal>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Generic::IEnumerable<TSource> ^ source, System::Threading::Tasks::ParallelOptions ^ parallelOptions, Func<TLocal> ^ localInit, Func<TSource, System::Threading::Tasks::ParallelLoopState ^, long, TLocal, TLocal> ^ body, Action<TLocal> ^ localFinally);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource,TLocal> (System.Collections.Generic.IEnumerable<TSource> source, System.Threading.Tasks.ParallelOptions parallelOptions, Func<TLocal> localInit, Func<TSource,System.Threading.Tasks.ParallelLoopState,long,TLocal,TLocal> body, Action<TLocal> localFinally);
static member ForEach : seq<'Source> * System.Threading.Tasks.ParallelOptions * Func<'Local> * Func<'Source, System.Threading.Tasks.ParallelLoopState, int64, 'Local, 'Local> * Action<'Local> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource, TLocal) (source As IEnumerable(Of TSource), parallelOptions As ParallelOptions, localInit As Func(Of TLocal), body As Func(Of TSource, ParallelLoopState, Long, TLocal, TLocal), localFinally As Action(Of TLocal)) As ParallelLoopResult
Type Parameters
- TSource
The type of the data in the source.
- TLocal
The type of the thread-local data.
Parameters
- source
- IEnumerable<TSource>
An enumerable data source.
- parallelOptions
- ParallelOptions
An object that configures the behavior of this operation.
- localInit
- Func<TLocal>
The function delegate that returns the initial state of the local data for each task.
- body
- Func<TSource,ParallelLoopState,Int64,TLocal,TLocal>
The delegate that is invoked once per iteration.
- localFinally
- Action<TLocal>
The delegate that performs a final action on the local state of each task.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The source
argument is null
.
-or-
The parallelOptions
argument is null
.
-or-
The body
argument is null
.
-or-
The localInit
argument is null
.
-or-
The localFinally
argument is null
.
The CancellationToken in the parallelOptions
argument is canceled.
The CancellationTokenSource associated with the CancellationToken in the parallelOptions
has been disposed.
The exception that contains all the individual exceptions thrown on all threads.
Remarks
The body
delegate is invoked once for each element in the source
enumerable. It is provided with the following parameters: the current element, a ParallelLoopState instance that may be used to break out of the loop prematurely, the current element's index (Int64), and some local state that may be shared amongst iterations that execute on the same thread.
The localInit
delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first body
invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the localFinally
delegate. The localFinally
delegate is invoked once per thread to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables.
The Parallel.ForEach method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying TaskScheduler object the chance to add, change, or remove threads that service the loop.
See also
Applies to
ForEach<TSource,TLocal>(Partitioner<TSource>, ParallelOptions, Func<TLocal>, Func<TSource,ParallelLoopState,TLocal,TLocal>, Action<TLocal>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation with thread-local data on a Partitioner in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated.
public:
generic <typename TSource, typename TLocal>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Concurrent::Partitioner<TSource> ^ source, System::Threading::Tasks::ParallelOptions ^ parallelOptions, Func<TLocal> ^ localInit, Func<TSource, System::Threading::Tasks::ParallelLoopState ^, TLocal, TLocal> ^ body, Action<TLocal> ^ localFinally);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource,TLocal> (System.Collections.Concurrent.Partitioner<TSource> source, System.Threading.Tasks.ParallelOptions parallelOptions, Func<TLocal> localInit, Func<TSource,System.Threading.Tasks.ParallelLoopState,TLocal,TLocal> body, Action<TLocal> localFinally);
static member ForEach : System.Collections.Concurrent.Partitioner<'Source> * System.Threading.Tasks.ParallelOptions * Func<'Local> * Func<'Source, System.Threading.Tasks.ParallelLoopState, 'Local, 'Local> * Action<'Local> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource, TLocal) (source As Partitioner(Of TSource), parallelOptions As ParallelOptions, localInit As Func(Of TLocal), body As Func(Of TSource, ParallelLoopState, TLocal, TLocal), localFinally As Action(Of TLocal)) As ParallelLoopResult
Type Parameters
- TSource
The type of the elements in source
.
- TLocal
The type of the thread-local data.
Parameters
- source
- Partitioner<TSource>
The partitioner that contains the original data source.
- parallelOptions
- ParallelOptions
An object that configures the behavior of this operation.
- localInit
- Func<TLocal>
The function delegate that returns the initial state of the local data for each task.
- body
- Func<TSource,ParallelLoopState,TLocal,TLocal>
The delegate that is invoked once per iteration.
- localFinally
- Action<TLocal>
The delegate that performs a final action on the local state of each task.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The source
argument is null
.
-or-
The parallelOptions
argument is null
.
-or-
The body
argument is null
.
-or-
The localInit
argument is null
.
-or-
The localFinally
argument is null
.
The SupportsDynamicPartitions property in the source
Partitioner returns false
or the partitioner returns null
partitions.
The exception that contains all the individual exceptions thrown on all threads.
The CancellationToken in the parallelOptions
argument is canceled.
The CancellationTokenSource associated with the CancellationToken in the parallelOptions
has been disposed.
Remarks
This overload is provided for scenarios where you want to override the default partitioning scheme. For example, small loop bodies might benefit from partitioning the range. The ForEach method expects custom partitioners to support dynamic partitioning. This overload is provided for scenarios with small loop bodies that might benefit from static range partitioning. Partitioners must support dynamic partitions. For more information, see Custom Partitioners for PLINQ and TPL and How to: Implement Dynamic Partitions.
The localInit
delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first body
invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the localFinally
delegate. The localFinally
delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables.
The Parallel.ForEach method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying TaskScheduler object the chance to add, change, or remove threads that service the loop.
See also
Applies to
ForEach<TSource,TLocal>(OrderablePartitioner<TSource>, ParallelOptions, Func<TLocal>, Func<TSource,ParallelLoopState,Int64,TLocal,TLocal>, Action<TLocal>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation with 64-bit indexes and with thread-local data on a OrderablePartitioner<TSource> in which iterations may run in parallel , loop options can be configured, and the state of the loop can be monitored and manipulated.
public:
generic <typename TSource, typename TLocal>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Concurrent::OrderablePartitioner<TSource> ^ source, System::Threading::Tasks::ParallelOptions ^ parallelOptions, Func<TLocal> ^ localInit, Func<TSource, System::Threading::Tasks::ParallelLoopState ^, long, TLocal, TLocal> ^ body, Action<TLocal> ^ localFinally);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource,TLocal> (System.Collections.Concurrent.OrderablePartitioner<TSource> source, System.Threading.Tasks.ParallelOptions parallelOptions, Func<TLocal> localInit, Func<TSource,System.Threading.Tasks.ParallelLoopState,long,TLocal,TLocal> body, Action<TLocal> localFinally);
static member ForEach : System.Collections.Concurrent.OrderablePartitioner<'Source> * System.Threading.Tasks.ParallelOptions * Func<'Local> * Func<'Source, System.Threading.Tasks.ParallelLoopState, int64, 'Local, 'Local> * Action<'Local> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource, TLocal) (source As OrderablePartitioner(Of TSource), parallelOptions As ParallelOptions, localInit As Func(Of TLocal), body As Func(Of TSource, ParallelLoopState, Long, TLocal, TLocal), localFinally As Action(Of TLocal)) As ParallelLoopResult
Type Parameters
- TSource
The type of the elements in source
.
- TLocal
The type of the thread-local data.
Parameters
The orderable partitioner that contains the original data source.
- parallelOptions
- ParallelOptions
An object that configures the behavior of this operation.
- localInit
- Func<TLocal>
The function delegate that returns the initial state of the local data for each task.
- body
- Func<TSource,ParallelLoopState,Int64,TLocal,TLocal>
The delegate that is invoked once per iteration.
- localFinally
- Action<TLocal>
The delegate that performs a final action on the local state of each task.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The source
argument is null
.
-or-
The parallelOptions
argument is null
.
-or-
The body
argument is null
.
-or-
The localInit
or localFinally
argument is null
.
The SupportsDynamicPartitions property in the source
Partitioner returns false
or the partitioner returns null
partitions.
The exception that contains all the individual exceptions thrown on all threads.
The CancellationToken in the parallelOptions
argument is canceled.
The CancellationTokenSource associated with the CancellationToken in the parallelOptions
has been disposed.
Remarks
This overload is provided for scenarios where you want to override the default partitioning scheme. For example, small loop bodies might benefit from partitioning the range. The ForEach method expects custom partitioners to support dynamic partitioning. For more information, see Custom Partitioners for PLINQ and TPL and How to: Implement Dynamic Partitions.
The localInit
delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first body
invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each thread returns a state value that is passed to the localFinally
delegate. The localFinally
delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables.
The Parallel.ForEach method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying TaskScheduler object the chance to add, change, or remove threads that service the loop.
See also
Applies to
ForEach<TSource,TLocal>(IEnumerable<TSource>, Func<TLocal>, Func<TSource,ParallelLoopState,TLocal,TLocal>, Action<TLocal>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation with thread-local data on an IEnumerable in which iterations may run in parallel, and the state of the loop can be monitored and manipulated.
public:
generic <typename TSource, typename TLocal>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TLocal> ^ localInit, Func<TSource, System::Threading::Tasks::ParallelLoopState ^, TLocal, TLocal> ^ body, Action<TLocal> ^ localFinally);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource,TLocal> (System.Collections.Generic.IEnumerable<TSource> source, Func<TLocal> localInit, Func<TSource,System.Threading.Tasks.ParallelLoopState,TLocal,TLocal> body, Action<TLocal> localFinally);
static member ForEach : seq<'Source> * Func<'Local> * Func<'Source, System.Threading.Tasks.ParallelLoopState, 'Local, 'Local> * Action<'Local> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource, TLocal) (source As IEnumerable(Of TSource), localInit As Func(Of TLocal), body As Func(Of TSource, ParallelLoopState, TLocal, TLocal), localFinally As Action(Of TLocal)) As ParallelLoopResult
Type Parameters
- TSource
The type of the data in the source.
- TLocal
The type of the thread-local data.
Parameters
- source
- IEnumerable<TSource>
An enumerable data source.
- localInit
- Func<TLocal>
The function delegate that returns the initial state of the local data for each task.
- body
- Func<TSource,ParallelLoopState,TLocal,TLocal>
The delegate that is invoked once per iteration.
- localFinally
- Action<TLocal>
The delegate that performs a final action on the local state of each task.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The source
argument is null
.
-or-
The body
argument is null
.
-or-
The localInit
argument is null
.
-or-
The localFinally
argument is null
.
The exception that contains all the individual exceptions thrown on all threads.
Examples
The following example shows how to use a ForEach method with local state:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class ForEachWithThreadLocal
{
// Demonstrated features:
// Parallel.ForEach()
// Thread-local state
// Expected results:
// This example sums up the elements of an int[] in parallel.
// Each thread maintains a local sum. When a thread is initialized, that local sum is set to 0.
// On every iteration the current element is added to the local sum.
// When a thread is done, it safely adds its local sum to the global sum.
// After the loop is complete, the global sum is printed out.
// Documentation:
// http://msdn.microsoft.com/library/dd990270(VS.100).aspx
static void Main()
{
// The sum of these elements is 40.
int[] input = { 4, 1, 6, 2, 9, 5, 10, 3 };
int sum = 0;
try
{
Parallel.ForEach(
input, // source collection
() => 0, // thread local initializer
(n, loopState, localSum) => // body
{
localSum += n;
Console.WriteLine("Thread={0}, n={1}, localSum={2}", Thread.CurrentThread.ManagedThreadId, n, localSum);
return localSum;
},
(localSum) => Interlocked.Add(ref sum, localSum) // thread local aggregator
);
Console.WriteLine("\nSum={0}", sum);
}
// 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.ForEach has thrown an exception. THIS WAS NOT EXPECTED.\n{0}", e);
}
}
}
Imports System.Threading
Imports System.Threading.Tasks
Module ForEachDemo
' Demonstrated features:
' Parallel.ForEach()
' Thread-local state
' Expected results:
' This example sums up the elements of an int[] in parallel.
' Each thread maintains a local sum. When a thread is initialized, that local sum is set to 0.
' On every iteration the current element is added to the local sum.
' When a thread is done, it safely adds its local sum to the global sum.
' After the loop is complete, the global sum is printed out.
' Documentation:
' http://msdn.microsoft.com/library/dd990270(VS.100).aspx
Private Sub ForEachDemo()
' The sum of these elements is 40.
Dim input As Integer() = {4, 1, 6, 2, 9, 5, _
10, 3}
Dim sum As Integer = 0
Try
' source collection
Parallel.ForEach(input,
Function()
' thread local initializer
Return 0
End Function,
Function(n, loopState, localSum)
' body
localSum += n
Console.WriteLine("Thread={0}, n={1}, localSum={2}", Thread.CurrentThread.ManagedThreadId, n, localSum)
Return localSum
End Function,
Sub(localSum)
' thread local aggregator
Interlocked.Add(sum, localSum)
End Sub)
Console.WriteLine(vbLf & "Sum={0}", sum)
Catch e As AggregateException
' 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.
Console.WriteLine("Parallel.ForEach has thrown an exception. THIS WAS NOT EXPECTED." & vbLf & "{0}", e)
End Try
End Sub
End Module
Remarks
The body
delegate is invoked once for each element in the source
enumerable. It is provided with the following parameters: the current element, a ParallelLoopState instance that may be used to break out of the loop prematurely, and some local state that may be shared amongst iterations that execute on the same thread.
The localInit
delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first body
invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the localFinally
delegate. The localFinally
delegate is invoked once per thread to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables.
The Parallel.ForEach method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying TaskScheduler object the chance to add, change, or remove threads that service the loop.
See also
Applies to
ForEach<TSource,TLocal>(IEnumerable<TSource>, Func<TLocal>, Func<TSource,ParallelLoopState,Int64,TLocal,TLocal>, Action<TLocal>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation with thread-local data on an IEnumerable in which iterations may run in parallel and the state of the loop can be monitored and manipulated.
public:
generic <typename TSource, typename TLocal>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TLocal> ^ localInit, Func<TSource, System::Threading::Tasks::ParallelLoopState ^, long, TLocal, TLocal> ^ body, Action<TLocal> ^ localFinally);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource,TLocal> (System.Collections.Generic.IEnumerable<TSource> source, Func<TLocal> localInit, Func<TSource,System.Threading.Tasks.ParallelLoopState,long,TLocal,TLocal> body, Action<TLocal> localFinally);
static member ForEach : seq<'Source> * Func<'Local> * Func<'Source, System.Threading.Tasks.ParallelLoopState, int64, 'Local, 'Local> * Action<'Local> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource, TLocal) (source As IEnumerable(Of TSource), localInit As Func(Of TLocal), body As Func(Of TSource, ParallelLoopState, Long, TLocal, TLocal), localFinally As Action(Of TLocal)) As ParallelLoopResult
Type Parameters
- TSource
The type of the data in the source.
- TLocal
The type of the thread-local data.
Parameters
- source
- IEnumerable<TSource>
An enumerable data source.
- localInit
- Func<TLocal>
The function delegate that returns the initial state of the local data for each task.
- body
- Func<TSource,ParallelLoopState,Int64,TLocal,TLocal>
The delegate that is invoked once per iteration.
- localFinally
- Action<TLocal>
The delegate that performs a final action on the local state of each task.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The source
argument is null
.
-or-
The body
argument is null
.
-or-
The localInit
argument is null
.
-or-
The localFinally
argument is null
.
The exception that contains all the individual exceptions thrown on all threads.
Remarks
The body
delegate is invoked once for each element in the source
enumerable. It is provided with the following parameters: the current element, a ParallelLoopState instance that may be used to break out of the loop prematurely, the current element's index (Int64), and some local state that may be shared amongst iterations that execute on the same thread.
The localInit
delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first body
invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the localFinally
delegate. The localFinally
delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables.
The Parallel.ForEach method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying TaskScheduler object the chance to add, change, or remove threads that service the loop.
See also
Applies to
ForEach<TSource,TLocal>(Partitioner<TSource>, Func<TLocal>, Func<TSource,ParallelLoopState,TLocal,TLocal>, Action<TLocal>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation with thread-local data on a Partitioner in which iterations may run in parallel and the state of the loop can be monitored and manipulated.
public:
generic <typename TSource, typename TLocal>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Concurrent::Partitioner<TSource> ^ source, Func<TLocal> ^ localInit, Func<TSource, System::Threading::Tasks::ParallelLoopState ^, TLocal, TLocal> ^ body, Action<TLocal> ^ localFinally);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource,TLocal> (System.Collections.Concurrent.Partitioner<TSource> source, Func<TLocal> localInit, Func<TSource,System.Threading.Tasks.ParallelLoopState,TLocal,TLocal> body, Action<TLocal> localFinally);
static member ForEach : System.Collections.Concurrent.Partitioner<'Source> * Func<'Local> * Func<'Source, System.Threading.Tasks.ParallelLoopState, 'Local, 'Local> * Action<'Local> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource, TLocal) (source As Partitioner(Of TSource), localInit As Func(Of TLocal), body As Func(Of TSource, ParallelLoopState, TLocal, TLocal), localFinally As Action(Of TLocal)) As ParallelLoopResult
Type Parameters
- TSource
The type of the elements in source
.
- TLocal
The type of the thread-local data.
Parameters
- source
- Partitioner<TSource>
The partitioner that contains the original data source.
- localInit
- Func<TLocal>
The function delegate that returns the initial state of the local data for each task.
- body
- Func<TSource,ParallelLoopState,TLocal,TLocal>
The delegate that is invoked once per iteration.
- localFinally
- Action<TLocal>
The delegate that performs a final action on the local state of each task.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The source
argument is null
.
-or-
The body
argument is null
.
-or-
The localInit
argument is null
.
-or-
The localFinally
argument is null
.
The SupportsDynamicPartitions property in the source
Partitioner returns false
or the partitioner returns null
partitions.
The exception that contains all the individual exceptions thrown on all threads.
Remarks
This overload is provided for scenarios where you want to override the default partitioning scheme. For example, small loop bodies might benefit from partitioning the range. The ForEach method expects custom partitioners to support dynamic partitioning. For more information, see Custom Partitioners for PLINQ and TPL and How to: Implement Dynamic Partitions.
The localInit
delegate is invoked once for each thread that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first body
invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the localFinally
delegate. The localFinally
delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables.
The Parallel.ForEach method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying TaskScheduler object the chance to add, change, or remove threads that service the loop.
See also
Applies to
ForEach<TSource,TLocal>(OrderablePartitioner<TSource>, Func<TLocal>, Func<TSource,ParallelLoopState,Int64,TLocal,TLocal>, Action<TLocal>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation with thread-local data on a OrderablePartitioner<TSource> in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated.
public:
generic <typename TSource, typename TLocal>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Concurrent::OrderablePartitioner<TSource> ^ source, Func<TLocal> ^ localInit, Func<TSource, System::Threading::Tasks::ParallelLoopState ^, long, TLocal, TLocal> ^ body, Action<TLocal> ^ localFinally);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource,TLocal> (System.Collections.Concurrent.OrderablePartitioner<TSource> source, Func<TLocal> localInit, Func<TSource,System.Threading.Tasks.ParallelLoopState,long,TLocal,TLocal> body, Action<TLocal> localFinally);
static member ForEach : System.Collections.Concurrent.OrderablePartitioner<'Source> * Func<'Local> * Func<'Source, System.Threading.Tasks.ParallelLoopState, int64, 'Local, 'Local> * Action<'Local> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource, TLocal) (source As OrderablePartitioner(Of TSource), localInit As Func(Of TLocal), body As Func(Of TSource, ParallelLoopState, Long, TLocal, TLocal), localFinally As Action(Of TLocal)) As ParallelLoopResult
Type Parameters
- TSource
The type of the elements in source
.
- TLocal
The type of the thread-local data.
Parameters
The orderable partitioner that contains the original data source.
- localInit
- Func<TLocal>
The function delegate that returns the initial state of the local data for each task.
- body
- Func<TSource,ParallelLoopState,Int64,TLocal,TLocal>
The delegate that is invoked once per iteration.
- localFinally
- Action<TLocal>
The delegate that performs a final action on the local state of each task.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The source
argument is null
.
-or-
The body
argument is null
.
-or-
The localInit
argument is null
.
-or-
The localFinally
argument is null
.
The SupportsDynamicPartitions property in the source
Partitioner returns false
or the partitioner returns null
partitions.
The exception that contains all the individual exceptions thrown on all threads.
Remarks
This overload is provided for scenarios where you want to override the default partitioning scheme. For example, small loop bodies might benefit from partitioning the range. The ForEach method expects custom partitioners to support dynamic partitioning. For more information, see Custom Partitioners for PLINQ and TPL and How to: Implement Dynamic Partitions.
The localInit
delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first body
invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the localFinally
delegate. The localFinally
delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables.
The Parallel.ForEach method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying TaskScheduler object the chance to add, change, or remove threads that service the loop.
See also
Applies to
ForEach<TSource>(IEnumerable<TSource>, ParallelOptions, Action<TSource>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation on an IEnumerable in which iterations may run in parallel and loop options can be configured.
public:
generic <typename TSource>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Generic::IEnumerable<TSource> ^ source, System::Threading::Tasks::ParallelOptions ^ parallelOptions, Action<TSource> ^ body);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource> (System.Collections.Generic.IEnumerable<TSource> source, System.Threading.Tasks.ParallelOptions parallelOptions, Action<TSource> body);
static member ForEach : seq<'Source> * System.Threading.Tasks.ParallelOptions * Action<'Source> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource) (source As IEnumerable(Of TSource), parallelOptions As ParallelOptions, body As Action(Of TSource)) As ParallelLoopResult
Type Parameters
- TSource
The type of the data in the source.
Parameters
- source
- IEnumerable<TSource>
An enumerable data source.
- parallelOptions
- ParallelOptions
An object that configures the behavior of this operation.
- body
- Action<TSource>
The delegate that is invoked once per iteration.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The CancellationToken in the parallelOptions
argument is canceled
The source
argument is null
.
-or-
The parallelOptions
argument is null
.
-or-
The body
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.
Remarks
The body
delegate is invoked once for each element in the source
enumerable. It is provided with the current element as a parameter.
See also
Applies to
ForEach<TSource>(IEnumerable<TSource>, ParallelOptions, Action<TSource,ParallelLoopState>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation on an IEnumerable in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated.
public:
generic <typename TSource>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Generic::IEnumerable<TSource> ^ source, System::Threading::Tasks::ParallelOptions ^ parallelOptions, Action<TSource, System::Threading::Tasks::ParallelLoopState ^> ^ body);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource> (System.Collections.Generic.IEnumerable<TSource> source, System.Threading.Tasks.ParallelOptions parallelOptions, Action<TSource,System.Threading.Tasks.ParallelLoopState> body);
static member ForEach : seq<'Source> * System.Threading.Tasks.ParallelOptions * Action<'Source, System.Threading.Tasks.ParallelLoopState> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource) (source As IEnumerable(Of TSource), parallelOptions As ParallelOptions, body As Action(Of TSource, ParallelLoopState)) As ParallelLoopResult
Type Parameters
- TSource
The type of the data in the source.
Parameters
- source
- IEnumerable<TSource>
An enumerable data source.
- parallelOptions
- ParallelOptions
An object that configures the behavior of this operation.
- body
- Action<TSource,ParallelLoopState>
The delegate that is invoked once per iteration.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The CancellationToken in the parallelOptions
argument is canceled
The source
argument is null
.
-or-
The parallelOptions
argument is null
.
-or-
The body
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.
Remarks
The body
delegate is invoked once for each element in the source
enumerable. It is provided with the following parameters: the current element, and a ParallelLoopState instance that may be used to break out of the loop prematurely.
See also
Applies to
ForEach<TSource>(OrderablePartitioner<TSource>, ParallelOptions, Action<TSource,ParallelLoopState,Int64>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation on a OrderablePartitioner<TSource> in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated.
public:
generic <typename TSource>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Concurrent::OrderablePartitioner<TSource> ^ source, System::Threading::Tasks::ParallelOptions ^ parallelOptions, Action<TSource, System::Threading::Tasks::ParallelLoopState ^, long> ^ body);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource> (System.Collections.Concurrent.OrderablePartitioner<TSource> source, System.Threading.Tasks.ParallelOptions parallelOptions, Action<TSource,System.Threading.Tasks.ParallelLoopState,long> body);
static member ForEach : System.Collections.Concurrent.OrderablePartitioner<'Source> * System.Threading.Tasks.ParallelOptions * Action<'Source, System.Threading.Tasks.ParallelLoopState, int64> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource) (source As OrderablePartitioner(Of TSource), parallelOptions As ParallelOptions, body As Action(Of TSource, ParallelLoopState, Long)) As ParallelLoopResult
Type Parameters
- TSource
The type of the elements in source
.
Parameters
The orderable partitioner that contains the original data source.
- parallelOptions
- ParallelOptions
An object that configures the behavior of this operation.
- body
- Action<TSource,ParallelLoopState,Int64>
The delegate that is invoked once per iteration.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The CancellationToken in the parallelOptions
argument is canceled
The source
argument is null
.
-or-
The parallelOptions
argument is null
.
-or-
The body
argument is null
.
The CancellationTokenSource associated with the CancellationToken in the parallelOptions
has been disposed.
The SupportsDynamicPartitions property in the source
orderable partitioner returns false
.
-or-
The KeysNormalized property in the source
orderable partitioner returns false
.
-or-
The exception that is thrown when any methods in the source
orderable partitioner return null
.
The exception that is thrown to contain an exception thrown from one of the specified delegates.
Remarks
This overload is provided for scenarios where you want to override the default partitioning scheme. For example, small loop bodies might benefit from partitioning the range. The Parallel.ForEach method expects custom partitioners to support dynamic partitioning. For more information, see Custom Partitioners for PLINQ and TPL and How to: Implement Dynamic Partitions.
See also
Applies to
ForEach<TSource>(Partitioner<TSource>, ParallelOptions, Action<TSource>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation on a Partitioner in which iterations may run in parallel and loop options can be configured.
public:
generic <typename TSource>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Concurrent::Partitioner<TSource> ^ source, System::Threading::Tasks::ParallelOptions ^ parallelOptions, Action<TSource> ^ body);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource> (System.Collections.Concurrent.Partitioner<TSource> source, System.Threading.Tasks.ParallelOptions parallelOptions, Action<TSource> body);
static member ForEach : System.Collections.Concurrent.Partitioner<'Source> * System.Threading.Tasks.ParallelOptions * Action<'Source> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource) (source As Partitioner(Of TSource), parallelOptions As ParallelOptions, body As Action(Of TSource)) As ParallelLoopResult
Type Parameters
- TSource
The type of the elements in source
.
Parameters
- source
- Partitioner<TSource>
The partitioner that contains the original data source.
- parallelOptions
- ParallelOptions
An object that configures the behavior of this operation.
- body
- Action<TSource>
The delegate that is invoked once per iteration.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The CancellationToken in the parallelOptions
argument is canceled.
The CancellationTokenSource associated with the CancellationToken in the parallelOptions
has been disposed.
The source
argument is null
.
-or-
The parallelOptions
argument is null
.
-or-
The body
argument is null
.
The SupportsDynamicPartitions property in the source
partitioner returns false
.
-or-
The exception that is thrown when any methods in the source
partitioner return null
.
The exception that is thrown to contain an exception thrown from one of the specified delegates.
Remarks
This overload is provided for scenarios where you want to override the default partitioning scheme. For example, small loop bodies might benefit from partitioning the range. The Parallel.ForEach method expects custom partitioners to support dynamic partitioning. For more information, see Custom Partitioners for PLINQ and TPL and How to: Implement Dynamic Partitions.
See also
Applies to
ForEach<TSource>(IEnumerable<TSource>, ParallelOptions, Action<TSource,ParallelLoopState,Int64>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation with 64-bit indexes on an IEnumerable in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated.
public:
generic <typename TSource>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Generic::IEnumerable<TSource> ^ source, System::Threading::Tasks::ParallelOptions ^ parallelOptions, Action<TSource, System::Threading::Tasks::ParallelLoopState ^, long> ^ body);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource> (System.Collections.Generic.IEnumerable<TSource> source, System.Threading.Tasks.ParallelOptions parallelOptions, Action<TSource,System.Threading.Tasks.ParallelLoopState,long> body);
static member ForEach : seq<'Source> * System.Threading.Tasks.ParallelOptions * Action<'Source, System.Threading.Tasks.ParallelLoopState, int64> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource) (source As IEnumerable(Of TSource), parallelOptions As ParallelOptions, body As Action(Of TSource, ParallelLoopState, Long)) As ParallelLoopResult
Type Parameters
- TSource
The type of the data in the source.
Parameters
- source
- IEnumerable<TSource>
An enumerable data source.
- parallelOptions
- ParallelOptions
An object that configures the behavior of this operation.
- body
- Action<TSource,ParallelLoopState,Int64>
The delegate that is invoked once per iteration.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The CancellationToken in the parallelOptions
argument is canceled
The source
argument is null
.
-or-
The parallelOptions
argument is null
.
-or-
The body
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.
Remarks
The body
delegate is invoked once for each element in the source
enumerable. It is provided with the following parameters: the current element, a ParallelLoopState instance that may be used to break out of the loop prematurely, and the current element's index (Int64).
See also
Applies to
ForEach<TSource>(Partitioner<TSource>, Action<TSource,ParallelLoopState>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation on a Partitioner in which iterations may run in parallel, and the state of the loop can be monitored and manipulated.
public:
generic <typename TSource>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Concurrent::Partitioner<TSource> ^ source, Action<TSource, System::Threading::Tasks::ParallelLoopState ^> ^ body);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource> (System.Collections.Concurrent.Partitioner<TSource> source, Action<TSource,System.Threading.Tasks.ParallelLoopState> body);
static member ForEach : System.Collections.Concurrent.Partitioner<'Source> * Action<'Source, System.Threading.Tasks.ParallelLoopState> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource) (source As Partitioner(Of TSource), body As Action(Of TSource, ParallelLoopState)) As ParallelLoopResult
Type Parameters
- TSource
The type of the elements in source
.
Parameters
- source
- Partitioner<TSource>
The partitioner that contains the original data source.
- body
- Action<TSource,ParallelLoopState>
The delegate that is invoked once per iteration.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The SupportsDynamicPartitions property in the source
partitioner returns false
.
-or-
A method in the source
partitioner returns null
.
-or-
The GetPartitions(Int32) method in the source
partitioner does not return the correct number of partitions.
The exception that is thrown to contain an exception thrown from one of the specified delegates.
Remarks
This overload is provided for scenarios where you want to override the default partitioning scheme. For example, small loop bodies might benefit from partitioning the range. The Parallel.ForEach method expects custom partitioners to support dynamic partitioning. For more information, see Custom Partitioners for PLINQ and TPL and How to: Implement Dynamic Partitions.
See also
Applies to
ForEach<TSource>(Partitioner<TSource>, Action<TSource>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation on a Partitioner in which iterations may run in parallel.
public:
generic <typename TSource>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Concurrent::Partitioner<TSource> ^ source, Action<TSource> ^ body);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource> (System.Collections.Concurrent.Partitioner<TSource> source, Action<TSource> body);
static member ForEach : System.Collections.Concurrent.Partitioner<'Source> * Action<'Source> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource) (source As Partitioner(Of TSource), body As Action(Of TSource)) As ParallelLoopResult
Type Parameters
- TSource
The type of the elements in source
.
Parameters
- source
- Partitioner<TSource>
The partitioner that contains the original data source.
- body
- Action<TSource>
The delegate that is invoked once per iteration.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The SupportsDynamicPartitions property in the source
partitioner returns false
.
-or-
The exception that is thrown when any methods in the source
partitioner return null
.
-or-
The GetPartitions(Int32) method in the source
partitioner does not return the correct number of partitions.
The exception that is thrown to contain an exception thrown from one of the specified delegates.
Examples
The following example shows how to implement a range partitioner for use with Parallel.ForEach:
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
class RangePartitionerDemo
{
static void Main()
{
Stopwatch sw = null;
long sum = 0;
long SUMTOP = 10000000;
// Try sequential for
sw = Stopwatch.StartNew();
for (long i = 0; i < SUMTOP; i++) sum += i;
sw.Stop();
Console.WriteLine("sequential for result = {0}, time = {1} ms", sum, sw.ElapsedMilliseconds);
// Try parallel for -- this is slow!
//sum = 0;
//sw = Stopwatch.StartNew();
//Parallel.For(0L, SUMTOP, (item) => Interlocked.Add(ref sum, item));
//sw.Stop();
//Console.WriteLine("parallel for result = {0}, time = {1} ms", sum, sw.ElapsedMilliseconds);
// Try parallel for with locals
sum = 0;
sw = Stopwatch.StartNew();
Parallel.For(0L, SUMTOP, () => 0L, (item, state, prevLocal) => prevLocal + item, local => Interlocked.Add(ref sum, local));
sw.Stop();
Console.WriteLine("parallel for w/locals result = {0}, time = {1} ms", sum, sw.ElapsedMilliseconds);
// Try range partitioner
sum = 0;
sw = Stopwatch.StartNew();
Parallel.ForEach(Partitioner.Create(0L, SUMTOP), (range) =>
{
long local = 0;
for (long i = range.Item1; i < range.Item2; i++) local += i;
Interlocked.Add(ref sum, local);
});
sw.Stop();
Console.WriteLine("range partitioner result = {0}, time = {1} ms", sum, sw.ElapsedMilliseconds);
}
}
Imports System.Collections.Concurrent
Imports System.Threading
Imports System.Threading.Tasks
Module RangePartitionerDemo
Sub Main()
Dim sw As Stopwatch = Nothing
Dim sum As Long = 0
Dim SUMTOP As Long = 10000000
' Try sequential for
sw = Stopwatch.StartNew()
For i As Long = 0 To SUMTOP - 1
sum += i
Next
sw.Stop()
Console.WriteLine("sequential for result = {0}, time = {1} ms", sum, sw.ElapsedMilliseconds)
' Try parallel for with locals
sum = 0
sw = Stopwatch.StartNew()
Parallel.For(0L, SUMTOP, Function() 0L, Function(item, state, prevLocal) prevLocal + item, Function(local) Interlocked.Add(sum, local))
sw.Stop()
Console.WriteLine("parallel for w/locals result = {0}, time = {1} ms", sum, sw.ElapsedMilliseconds)
' Try range partitioner
sum = 0
sw = Stopwatch.StartNew()
Parallel.ForEach(Partitioner.Create(0L, SUMTOP),
Sub(range)
Dim local As Long = 0
For i As Long = range.Item1 To range.Item2 - 1
local += i
Next
Interlocked.Add(sum, local)
End Sub)
sw.Stop()
Console.WriteLine("range partitioner result = {0}, time = {1} ms", sum, sw.ElapsedMilliseconds)
End Sub
End Module
Remarks
This overload is provided for scenarios where you want to override the default partitioning scheme. For example, small loop bodies might benefit from partitioning the range. The Parallel.ForEach method expects custom partitioners to support dynamic partitioning. For more information, see Custom Partitioners for PLINQ and TPL and How to: Implement Dynamic Partitions.
See also
Applies to
ForEach<TSource>(IEnumerable<TSource>, Action<TSource,ParallelLoopState,Int64>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation with 64-bit indexes on an IEnumerable in which iterations may run in parallel, and the state of the loop can be monitored and manipulated.
public:
generic <typename TSource>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Generic::IEnumerable<TSource> ^ source, Action<TSource, System::Threading::Tasks::ParallelLoopState ^, long> ^ body);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource> (System.Collections.Generic.IEnumerable<TSource> source, Action<TSource,System.Threading.Tasks.ParallelLoopState,long> body);
static member ForEach : seq<'Source> * Action<'Source, System.Threading.Tasks.ParallelLoopState, int64> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource) (source As IEnumerable(Of TSource), body As Action(Of TSource, ParallelLoopState, Long)) As ParallelLoopResult
Type Parameters
- TSource
The type of the data in the source.
Parameters
- source
- IEnumerable<TSource>
An enumerable data source.
- body
- Action<TSource,ParallelLoopState,Int64>
The delegate that is invoked once per iteration.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The exception that contains all the individual exceptions thrown on all threads.
Remarks
The body
delegate is invoked once for each element in the source
enumerable. It is provided with the following parameters: the current element, a ParallelLoopState instance that may be used to break out of the loop prematurely, and the current element's index (Int64).
See also
Applies to
ForEach<TSource>(OrderablePartitioner<TSource>, Action<TSource,ParallelLoopState,Int64>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation on a OrderablePartitioner<TSource> in which iterations may run in parallel and the state of the loop can be monitored and manipulated.
public:
generic <typename TSource>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Concurrent::OrderablePartitioner<TSource> ^ source, Action<TSource, System::Threading::Tasks::ParallelLoopState ^, long> ^ body);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource> (System.Collections.Concurrent.OrderablePartitioner<TSource> source, Action<TSource,System.Threading.Tasks.ParallelLoopState,long> body);
static member ForEach : System.Collections.Concurrent.OrderablePartitioner<'Source> * Action<'Source, System.Threading.Tasks.ParallelLoopState, int64> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource) (source As OrderablePartitioner(Of TSource), body As Action(Of TSource, ParallelLoopState, Long)) As ParallelLoopResult
Type Parameters
- TSource
The type of the elements in source
.
Parameters
The orderable partitioner that contains the original data source.
- body
- Action<TSource,ParallelLoopState,Int64>
The delegate that is invoked once per iteration.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The SupportsDynamicPartitions property in the source
orderable partitioner returns false
.
-or-
The KeysNormalized property in the source orderable partitioner returns false
.
-or-
Any methods in the source orderable partitioner return null
.
The exception thrown from one of the specified delegates.
Remarks
This overload is provided for scenarios where you want to override the default partitioning scheme. For example, small loop bodies might benefit from partitioning the range. The Parallel.ForEach method expects custom partitioners to support dynamic partitioning. For more information, see Custom Partitioners for PLINQ and TPL and How to: Implement Dynamic Partitions.
See also
Applies to
ForEach<TSource>(IEnumerable<TSource>, Action<TSource>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation on an IEnumerable in which iterations may run in parallel.
public:
generic <typename TSource>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Generic::IEnumerable<TSource> ^ source, Action<TSource> ^ body);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource> (System.Collections.Generic.IEnumerable<TSource> source, Action<TSource> body);
static member ForEach : seq<'Source> * Action<'Source> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource) (source As IEnumerable(Of TSource), body As Action(Of TSource)) As ParallelLoopResult
Type Parameters
- TSource
The type of the data in the source.
Parameters
- source
- IEnumerable<TSource>
An enumerable data source.
- body
- Action<TSource>
The delegate that is invoked once per iteration.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The exception that contains all the individual exceptions thrown on all threads.
Examples
The following example uses the ForEach<TSource>(IEnumerable<TSource>, Action<TSource>) method to count the number of vowels and non-white-space characters in a text file. In this case, the ParallelLoopResult value returned by the method is ignored. Note that, because operations can run in parallel, you must ensure that incrementing the counter variables is an atomic operation, and that multiple threads do not attempt to access the counter variables simultaneously. For this purpose, the example uses the lock
statement (in C#) and the SyncLock
statement (in Visual Basic).
using System;
using System.IO;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
Task<String> task = ReadCharacters(@".\CallOfTheWild.txt");
String text = task.Result;
int nVowels = 0;
int nNonWhiteSpace = 0;
Object obj = new Object();
ParallelLoopResult result = Parallel.ForEach(text,
(ch) => {
Char uCh = Char.ToUpper(ch);
if ("AEIOUY".IndexOf(uCh) >= 0) {
lock (obj) {
nVowels++;
}
}
if (! Char.IsWhiteSpace(uCh)) {
lock (obj) {
nNonWhiteSpace++;
}
}
} );
Console.WriteLine("Total characters: {0,10:N0}", text.Length);
Console.WriteLine("Total vowels: {0,10:N0}", nVowels);
Console.WriteLine("Total non-white-space: {0,10:N0}", nNonWhiteSpace);
}
private static async Task<String> ReadCharacters(String fn)
{
String text;
using (StreamReader sr = new StreamReader(fn)) {
text = await sr.ReadToEndAsync();
}
return text;
}
}
// The example displays output like the following:
// Total characters: 198,548
// Total vowels: 58,421
// Total non-white-space: 159,461
Imports System.IO
Imports System.Threading.Tasks
Module Example
Public Sub Main()
Dim task As Task(Of String) = ReadCharacters(".\CallOfTheWild.txt")
Dim text As String = task.Result
Dim nVowels As Integer = 0
Dim nNonWhiteSpace As Integer = 0
Dim obj As New Object()
Dim result As ParallelLoopResult = Parallel.ForEach(text,
Sub(ch)
Dim uCh As Char = Char.ToUpper(ch)
If "AEIOUY".IndexOf(uCh) >= 0 Then
SyncLock obj
nVowels += 1
End SyncLock
End If
If Not Char.IsWhiteSpace(uCh) Then
SyncLock obj
nNonWhiteSpace += 1
End SyncLock
End If
End Sub)
Console.WriteLine("Total characters: {0,10:N0}", text.Length)
Console.WriteLine("Total vowels: {0,10:N0}", nVowels)
Console.WriteLine("Total non-white space: {0,10:N0}", nNonWhiteSpace)
End Sub
Private Async Function ReadCharacters(fn As String) As Task(Of String)
Dim text As String
Using sr As New StreamReader(fn)
text = Await sr.ReadToEndAsync()
End Using
Return text
End Function
End Module
' The output from the example resembles the following:
' Total characters: 198,548
' Total vowels: 58,421
' Total non-white space: 159,461
Remarks
The body
delegate is invoked once for each element in the source
enumerable. It is provided with the current element as a parameter.
See also
Applies to
ForEach<TSource>(Partitioner<TSource>, ParallelOptions, Action<TSource,ParallelLoopState>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation on a Partitioner in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated.
public:
generic <typename TSource>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Concurrent::Partitioner<TSource> ^ source, System::Threading::Tasks::ParallelOptions ^ parallelOptions, Action<TSource, System::Threading::Tasks::ParallelLoopState ^> ^ body);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource> (System.Collections.Concurrent.Partitioner<TSource> source, System.Threading.Tasks.ParallelOptions parallelOptions, Action<TSource,System.Threading.Tasks.ParallelLoopState> body);
static member ForEach : System.Collections.Concurrent.Partitioner<'Source> * System.Threading.Tasks.ParallelOptions * Action<'Source, System.Threading.Tasks.ParallelLoopState> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource) (source As Partitioner(Of TSource), parallelOptions As ParallelOptions, body As Action(Of TSource, ParallelLoopState)) As ParallelLoopResult
Type Parameters
- TSource
The type of the elements in source
.
Parameters
- source
- Partitioner<TSource>
The partitioner that contains the original data source.
- parallelOptions
- ParallelOptions
An object that configures the behavior of this operation.
- body
- Action<TSource,ParallelLoopState>
The delegate that is invoked once per iteration.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The CancellationToken in the parallelOptions
argument is canceled.
The CancellationTokenSource associated with the CancellationToken in the parallelOptions
has been disposed.
The source
argument is null
.
-or-
The parallelOptions
argument is null
.
-or-
The body
argument is null
.
The SupportsDynamicPartitions property in the source
partitioner returns false
.
-or-
The exception that is thrown when any methods in the source
partitioner return null
.
The exception that is thrown to contain an exception thrown from one of the specified delegates.
Remarks
This overload is provided for scenarios where you want to override the default partitioning scheme. For example, small loop bodies might benefit from partitioning the range. The Parallel.ForEach method expects custom partitioners to support dynamic partitioning. For more information, see Custom Partitioners for PLINQ and TPL and How to: Implement Dynamic Partitions.
See also
Applies to
ForEach<TSource>(IEnumerable<TSource>, Action<TSource,ParallelLoopState>)
- Source:
- Parallel.cs
- Source:
- Parallel.cs
- Source:
- Parallel.cs
Executes a foreach
(For Each
in Visual Basic) operation on an IEnumerable in which iterations may run in parallel, and the state of the loop can be monitored and manipulated.
public:
generic <typename TSource>
static System::Threading::Tasks::ParallelLoopResult ForEach(System::Collections::Generic::IEnumerable<TSource> ^ source, Action<TSource, System::Threading::Tasks::ParallelLoopState ^> ^ body);
public static System.Threading.Tasks.ParallelLoopResult ForEach<TSource> (System.Collections.Generic.IEnumerable<TSource> source, Action<TSource,System.Threading.Tasks.ParallelLoopState> body);
static member ForEach : seq<'Source> * Action<'Source, System.Threading.Tasks.ParallelLoopState> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function ForEach(Of TSource) (source As IEnumerable(Of TSource), body As Action(Of TSource, ParallelLoopState)) As ParallelLoopResult
Type Parameters
- TSource
The type of the data in the source.
Parameters
- source
- IEnumerable<TSource>
An enumerable data source.
- body
- Action<TSource,ParallelLoopState>
The delegate that is invoked once per iteration.
Returns
A structure that contains information about which portion of the loop completed.
Exceptions
The exception that contains all the individual exceptions thrown on all threads.
Remarks
The body
delegate is invoked once for each element in the source
enumerable. It is provided with the following parameters: the current element, and a ParallelLoopState instance that may be used to break out of the loop prematurely.