Parallel.For メソッド

定義

反復処理が並列で実行される可能性のある for ループを実行します。

オーバーロード

For(Int32, Int32, Action<Int32,ParallelLoopState>)

反復処理が並列で実行される可能性があり、ループの状態を監視および操作できる for ループを実行します。

For(Int32, Int32, Action<Int32>)

反復処理が並列で実行される可能性のある for ループを実行します。

For(Int64, Int64, Action<Int64,ParallelLoopState>)

反復処理が並列で実行される可能性があり、ループの状態を監視および操作できる、64 ビットのインデックスを持つ for ループを実行します。

For(Int64, Int64, Action<Int64>)

反復処理が並列で実行される可能性のある、64 ビットのインデックスを持つ for ループを実行します。

For(Int32, Int32, ParallelOptions, Action<Int32,ParallelLoopState>)

反復処理が並列で実行される可能性があり、ループ オプションを構成でき、ループの状態を監視および操作できる for ループを実行します。

For(Int32, Int32, ParallelOptions, Action<Int32>)

反復処理が並列で実行される可能性があり、ループ オプションを構成できる for ループを実行します。

For(Int64, Int64, ParallelOptions, Action<Int64,ParallelLoopState>)

反復処理が並列で実行される可能性があり、ループ オプションを構成でき、ループの状態を監視および操作できる、64 ビットのインデックスを持つ for ループを実行します。

For(Int64, Int64, ParallelOptions, Action<Int64>)

イテレーションが並列で実行される可能性があり、ループ オプションを構成できる、64 ビットのインデックスを持つ for ループを実行します。

For<TLocal>(Int32, Int32, Func<TLocal>, Func<Int32,ParallelLoopState,TLocal,TLocal>, Action<TLocal>)

反復処理が並列で実行される可能性があり、ループの状態を監視および操作できる、スレッド ローカル データを持つ for ループを実行します。

For<TLocal>(Int64, Int64, Func<TLocal>, Func<Int64,ParallelLoopState,TLocal,TLocal>, Action<TLocal>)

反復処理が並列で実行される可能性があり、ループの状態を監視および操作できる、64 ビットのインデックスとスレッド ローカル データを持つ for ループを実行します。

For<TLocal>(Int32, Int32, ParallelOptions, Func<TLocal>, Func<Int32,ParallelLoopState,TLocal,TLocal>, Action<TLocal>)

反復処理が並列で実行される可能性があり、ループ オプションを構成でき、ループの状態を監視および操作できる、スレッド ローカル データを持つ for ループを実行します。

For<TLocal>(Int64, Int64, ParallelOptions, Func<TLocal>, Func<Int64,ParallelLoopState,TLocal,TLocal>, Action<TLocal>)

反復処理が並列で実行される可能性があり、ループ オプションを構成でき、ループの状態を監視および操作できる、64 ビットのインデックスとスレッド ローカル データを持つ for ループを実行します。

For(Int32, Int32, Action<Int32,ParallelLoopState>)

反復処理が並列で実行される可能性があり、ループの状態を監視および操作できる for ループを実行します。

public:
 static System::Threading::Tasks::ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int, System::Threading::Tasks::ParallelLoopState ^> ^ body);
public static System.Threading.Tasks.ParallelLoopResult For (int fromInclusive, int toExclusive, Action<int,System.Threading.Tasks.ParallelLoopState> body);
static member For : int * int * Action<int, System.Threading.Tasks.ParallelLoopState> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function For (fromInclusive As Integer, toExclusive As Integer, body As Action(Of Integer, ParallelLoopState)) As ParallelLoopResult

パラメーター

fromInclusive
Int32

開始インデックス。ここで指定したインデックスから処理が開始されます。

toExclusive
Int32

終了インデックス。ここで指定したインデックスの前のインデックスまで処理が行われます。

body
Action<Int32,ParallelLoopState>

1 回のイテレーションにつき 1 回呼び出されるデリゲート。

戻り値

完了したループの部分に関する情報を格納している構造。

例外

body 引数が null です。

すべてのスレッドでスローされたすべての個別の例外を含む例外。

次の例では、ループの最大 100 回の反復を並列で実行します。 各イテレーションは、1 から 1,000 ミリ秒までのランダムな間隔で一時停止します。 ランダムに生成された値は、メソッドが呼び出されるループのイテレーションを ParallelLoopState.Break 決定します。 この例の出力に示すように、 メソッドの呼び出し後に、プロパティ値より大きいインデックスを ParallelLoopState.LowestBreakIteration 持つイテレーションは ParallelLoopState.Break 開始されません。

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
    public static void Main()
    {
        var rnd = new Random();
        int breakIndex = rnd.Next(1, 11);

        Console.WriteLine($"Will call Break at iteration {breakIndex}\n");

        var result = Parallel.For(1, 101, (i, state) => 
        {
            Console.WriteLine($"Beginning iteration {i}");
            int delay;
            lock (rnd)
                delay = rnd.Next(1, 1001);
            Thread.Sleep(delay);

            if (state.ShouldExitCurrentIteration)
            {
                if (state.LowestBreakIteration < i)
                    return;
            }

            if (i == breakIndex)
            {
                Console.WriteLine($"Break in iteration {i}");
                state.Break();
            }

            Console.WriteLine($"Completed iteration {i}");
        });

        if (result.LowestBreakIteration.HasValue)
            Console.WriteLine($"\nLowest Break Iteration: {result.LowestBreakIteration}");
        else
            Console.WriteLine($"\nNo lowest break iteration.");
    }
}
// The example displays output like the following:
//       Will call Break at iteration 8
//
//       Beginning iteration 1
//       Beginning iteration 13
//       Beginning iteration 97
//       Beginning iteration 25
//       Beginning iteration 49
//       Beginning iteration 37
//       Beginning iteration 85
//       Beginning iteration 73
//       Beginning iteration 61
//       Completed iteration 85
//       Beginning iteration 86
//       Completed iteration 61
//       Beginning iteration 62
//       Completed iteration 86
//       Beginning iteration 87
//       Completed iteration 37
//       Beginning iteration 38
//       Completed iteration 38
//       Beginning iteration 39
//       Completed iteration 25
//       Beginning iteration 26
//       Completed iteration 26
//       Beginning iteration 27
//       Completed iteration 73
//       Beginning iteration 74
//       Completed iteration 62
//       Beginning iteration 63
//       Completed iteration 39
//       Beginning iteration 40
//       Completed iteration 40
//       Beginning iteration 41
//       Completed iteration 13
//       Beginning iteration 14
//       Completed iteration 1
//       Beginning iteration 2
//       Completed iteration 97
//       Beginning iteration 98
//       Completed iteration 49
//       Beginning iteration 50
//       Completed iteration 87
//       Completed iteration 27
//       Beginning iteration 28
//       Completed iteration 50
//       Beginning iteration 51
//       Beginning iteration 88
//       Completed iteration 14
//       Beginning iteration 15
//       Completed iteration 15
//       Completed iteration 2
//       Beginning iteration 3
//       Beginning iteration 16
//       Completed iteration 63
//       Beginning iteration 64
//       Completed iteration 74
//       Beginning iteration 75
//       Completed iteration 41
//       Beginning iteration 42
//       Completed iteration 28
//       Beginning iteration 29
//       Completed iteration 29
//       Beginning iteration 30
//       Completed iteration 98
//       Beginning iteration 99
//       Completed iteration 64
//       Beginning iteration 65
//       Completed iteration 42
//       Beginning iteration 43
//       Completed iteration 88
//       Beginning iteration 89
//       Completed iteration 51
//       Beginning iteration 52
//       Completed iteration 16
//       Beginning iteration 17
//       Completed iteration 43
//       Beginning iteration 44
//       Completed iteration 44
//       Beginning iteration 45
//       Completed iteration 99
//       Beginning iteration 4
//       Completed iteration 3
//       Beginning iteration 8
//       Completed iteration 4
//       Beginning iteration 5
//       Completed iteration 52
//       Beginning iteration 53
//       Completed iteration 75
//       Beginning iteration 76
//       Completed iteration 76
//       Beginning iteration 77
//       Completed iteration 65
//       Beginning iteration 66
//       Completed iteration 5
//       Beginning iteration 6
//       Completed iteration 89
//       Beginning iteration 90
//       Completed iteration 30
//       Beginning iteration 31
//       Break in iteration 8
//       Completed iteration 8
//       Completed iteration 6
//       Beginning iteration 7
//       Completed iteration 7
//
//       Lowest Break Iteration: 8
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim breakIndex As Integer = rnd.Next(1, 11)
      Dim lowest As New Nullable(Of Long)()

      Console.WriteLine("Will call Break at iteration {0}", breakIndex)
      Console.WriteLine()

      Dim result = Parallel.For(1, 101, Sub(i, state)
                                            Console.WriteLine("Beginning iteration {0}", i)
                                            Dim delay As Integer
                                            Monitor.Enter(rnd)
                                               delay = rnd.Next(1, 1001)
                                            Monitor.Exit(rnd)
                                            Thread.Sleep(delay)

                                            If state.ShouldExitCurrentIteration Then
                                               If state.LowestBreakIteration < i Then
                                                  Return
                                               End If
                                            End If

                                            If i = breakIndex Then
                                               Console.WriteLine("Break in iteration {0}", i)
                                               state.Break()
                                               If state.LowestBreakIteration.HasValue Then
                                                  If lowest < state.LowestBreakIteration Then
                                                     lowest = state.LowestBreakIteration
                                                  Else
                                                     lowest = state.LowestBreakIteration
                                                  End If
                                               End If
                                            End If

                                            Console.WriteLine("Completed iteration {0}", i)
                                       End Sub )
         Console.WriteLine()
         If lowest.HasValue Then
            Console.WriteLine("Lowest Break Iteration: {0}", lowest)
         Else
            Console.WriteLine("No lowest break iteration.")
         End If
   End Sub
End Module
' The example displays output like the following:
'       Will call Break at iteration 8
'
'       Beginning iteration 1
'       Beginning iteration 13
'       Beginning iteration 97
'       Beginning iteration 25
'       Beginning iteration 49
'       Beginning iteration 37
'       Beginning iteration 85
'       Beginning iteration 73
'       Beginning iteration 61
'       Completed iteration 85
'       Beginning iteration 86
'       Completed iteration 61
'       Beginning iteration 62
'       Completed iteration 86
'       Beginning iteration 87
'       Completed iteration 37
'       Beginning iteration 38
'       Completed iteration 38
'       Beginning iteration 39
'       Completed iteration 25
'       Beginning iteration 26
'       Completed iteration 26
'       Beginning iteration 27
'       Completed iteration 73
'       Beginning iteration 74
'       Completed iteration 62
'       Beginning iteration 63
'       Completed iteration 39
'       Beginning iteration 40
'       Completed iteration 40
'       Beginning iteration 41
'       Completed iteration 13
'       Beginning iteration 14
'       Completed iteration 1
'       Beginning iteration 2
'       Completed iteration 97
'       Beginning iteration 98
'       Completed iteration 49
'       Beginning iteration 50
'       Completed iteration 87
'       Completed iteration 27
'       Beginning iteration 28
'       Completed iteration 50
'       Beginning iteration 51
'       Beginning iteration 88
'       Completed iteration 14
'       Beginning iteration 15
'       Completed iteration 15
'       Completed iteration 2
'       Beginning iteration 3
'       Beginning iteration 16
'       Completed iteration 63
'       Beginning iteration 64
'       Completed iteration 74
'       Beginning iteration 75
'       Completed iteration 41
'       Beginning iteration 42
'       Completed iteration 28
'       Beginning iteration 29
'       Completed iteration 29
'       Beginning iteration 30
'       Completed iteration 98
'       Beginning iteration 99
'       Completed iteration 64
'       Beginning iteration 65
'       Completed iteration 42
'       Beginning iteration 43
'       Completed iteration 88
'       Beginning iteration 89
'       Completed iteration 51
'       Beginning iteration 52
'       Completed iteration 16
'       Beginning iteration 17
'       Completed iteration 43
'       Beginning iteration 44
'       Completed iteration 44
'       Beginning iteration 45
'       Completed iteration 99
'       Beginning iteration 4
'       Completed iteration 3
'       Beginning iteration 8
'       Completed iteration 4
'       Beginning iteration 5
'       Completed iteration 52
'       Beginning iteration 53
'       Completed iteration 75
'       Beginning iteration 76
'       Completed iteration 76
'       Beginning iteration 77
'       Completed iteration 65
'       Beginning iteration 66
'       Completed iteration 5
'       Beginning iteration 6
'       Completed iteration 89
'       Beginning iteration 90
'       Completed iteration 30
'       Beginning iteration 31
'       Break in iteration 8
'       Completed iteration 8
'       Completed iteration 6
'       Beginning iteration 7
'       Completed iteration 7
'
'       Lowest Break Iteration: 8

メソッドの呼び出し時ParallelLoopState.Breakにループのイテレーションが引き続き実行される可能性が高いため、各イテレーションは プロパティをParallelLoopState.ShouldExitCurrentIteration呼び出して、別のイテレーションで メソッドが呼び出ParallelLoopState.Breakされたかどうかをチェックします。 プロパティ値が の場合、イテレーションは trueプロパティの値を ParallelLoopState.LowestBreakIteration チェックし、現在のイテレーションのインデックス値より大きい場合は、直ちに を返します。

注釈

デリゲートは body 、イテレーション範囲内fromInclusiveの値 (、 toExclusive) ごとに 1 回呼び出されます。 次の 2 つの引数を指定します。

  • Int32反復回数を表す値。

  • ParallelLoopStateループから途中で抜け出すために使用できるインスタンス。 オブジェクトは ParallelLoopState コンパイラによって作成されます。ユーザー コードではインスタンス化できません。

メソッドを Break 呼び出すと、現在の for メソッドの後でイテレーションを実行する必要がないことを操作に通知します。 ただし、現在のイテレーションより前のすべてのイテレーションは、まだ実行されていない場合でも実行する必要があります。

したがって、 を呼び出 Break すことは、C# のような言語で従来 for のループ内で中断操作を使用するのと似ていますが、完全な代替ではありません。たとえば、現在のループの後の反復が確実に実行されないという保証はありません。

現在のイテレーションの前にすべてのイテレーションを実行する必要がない場合は、 を使用する代わりに メソッドを Stop 使用 Breakします。 を呼び出 Stop すと、必要なすべての作業が既に完了しているため、現在のイテレーションの前か後かに関係なく、残りのすべてのイテレーションが破棄される可能性があることをループに通知 for します。 ただし、 と Break同様に、他のイテレーションが実行されない保証はありません。

ループが途中で終了した場合、 ParallelLoopResult 返される構造体にはループの完了に関する関連情報が含まれます。

が 以上toExclusiveの場合fromInclusive、メソッドはイテレーションを実行せずにすぐにを返します。

こちらもご覧ください

適用対象

For(Int32, Int32, Action<Int32>)

反復処理が並列で実行される可能性のある for ループを実行します。

public:
 static System::Threading::Tasks::ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int> ^ body);
public static System.Threading.Tasks.ParallelLoopResult For (int fromInclusive, int toExclusive, Action<int> body);
static member For : int * int * Action<int> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function For (fromInclusive As Integer, toExclusive As Integer, body As Action(Of Integer)) As ParallelLoopResult

パラメーター

fromInclusive
Int32

開始インデックス。ここで指定したインデックスから処理が開始されます。

toExclusive
Int32

終了インデックス。ここで指定したインデックスの前のインデックスまで処理が行われます。

body
Action<Int32>

1 回のイテレーションにつき 1 回呼び出されるデリゲート。

戻り値

完了したループの部分に関する情報を格納している構造。

例外

body 引数が null です。

すべてのスレッドでスローされたすべての個別の例外を含む例外。

次の例では、 メソッドを For 使用して、ランダムなバイト値を生成し、その合計を計算するデリゲートの 100 個の呼び出しに使用します。

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      ParallelLoopResult result = Parallel.For(0, 100, ctr => { Random rnd = new Random(ctr * 100000);
                                                                Byte[] bytes = new Byte[100];
                                                                rnd.NextBytes(bytes);
                                                                int sum = 0;
                                                                foreach(var byt in bytes)
                                                                    sum += byt;
                                                                Console.WriteLine("Iteration {0,2}: {1:N0}", ctr, sum);
                                                              });
      Console.WriteLine("Result: {0}", result.IsCompleted ? "Completed Normally" : 
                                                             String.Format("Completed to {0}", result.LowestBreakIteration));
   }
}
// The following is a portion of the output displayed by the example:
//       Iteration  0: 12,509
//       Iteration 50: 12,823
//       Iteration 51: 11,275
//       Iteration 52: 12,531
//       Iteration  1: 13,007
//       Iteration 53: 13,799
//       Iteration  4: 12,945
//       Iteration  2: 13,246
//       Iteration 54: 13,008
//       Iteration 55: 12,727
//       Iteration 56: 13,223
//       Iteration 57: 13,717
//       Iteration  5: 12,679
//       Iteration  3: 12,455
//       Iteration 58: 12,669
//       Iteration 59: 11,882
//       Iteration  6: 13,167
//       ...
//       Iteration 92: 12,275
//       Iteration 93: 13,282
//       Iteration 94: 12,745
//       Iteration 95: 11,957
//       Iteration 96: 12,455
//       Result: Completed Normally
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim result As ParallelLoopResult = Parallel.For(0, 100, Sub(ctr)
                                                                 Dim rnd As New Random(ctr * 100000)
                                                                 Dim bytes(99) As Byte
                                                                 rnd.NextBytes(bytes)
                                                                 Dim sum As Integer
                                                                 For Each byt In bytes
                                                                    sum += byt
                                                                 Next
                                                                 Console.WriteLine("Iteration {0,2}: {1:N0}", ctr, sum)
                                                              End Sub)
      Console.WriteLine("Result: {0}", If(result.IsCompleted, "Completed Normally", 
                                                             String.Format("Completed to {0}", result.LowestBreakIteration)))
   End Sub
End Module
' The following is a portion of the output displayed by the example:
'       Iteration  0: 12,509
'       Iteration 50: 12,823
'       Iteration 51: 11,275
'       Iteration 52: 12,531
'       Iteration  1: 13,007
'       Iteration 53: 13,799
'       Iteration  4: 12,945
'       Iteration  2: 13,246
'       Iteration 54: 13,008
'       Iteration 55: 12,727
'       Iteration 56: 13,223
'       Iteration 57: 13,717
'       Iteration  5: 12,679
'       Iteration  3: 12,455
'       Iteration 58: 12,669
'       Iteration 59: 11,882
'       Iteration  6: 13,167
'       ...
'       Iteration 92: 12,275
'       Iteration 93: 13,282
'       Iteration 94: 12,745
'       Iteration 95: 11,957
'       Iteration 96: 12,455
'       Result: Completed Normally

注釈

デリゲートは body 、イテレーション範囲内fromInclusiveの値 (、 toExclusive) ごとに 1 回呼び出されます。 これは、反復カウント (Int32) をパラメーターとして指定します。

が 以上toExclusiveの場合fromInclusive、メソッドはイテレーションを実行せずにすぐにを返します。

こちらもご覧ください

適用対象

For(Int64, Int64, Action<Int64,ParallelLoopState>)

反復処理が並列で実行される可能性があり、ループの状態を監視および操作できる、64 ビットのインデックスを持つ for ループを実行します。

public:
 static System::Threading::Tasks::ParallelLoopResult For(long fromInclusive, long toExclusive, Action<long, System::Threading::Tasks::ParallelLoopState ^> ^ body);
public static System.Threading.Tasks.ParallelLoopResult For (long fromInclusive, long toExclusive, Action<long,System.Threading.Tasks.ParallelLoopState> body);
static member For : int64 * int64 * Action<int64, System.Threading.Tasks.ParallelLoopState> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function For (fromInclusive As Long, toExclusive As Long, body As Action(Of Long, ParallelLoopState)) As ParallelLoopResult

パラメーター

fromInclusive
Int64

開始インデックス。ここで指定したインデックスから処理が開始されます。

toExclusive
Int64

終了インデックス。ここで指定したインデックスの前のインデックスまで処理が行われます。

body
Action<Int64,ParallelLoopState>

1 回のイテレーションにつき 1 回呼び出されるデリゲート。

戻り値

完了したループの部分に関する情報を格納している ParallelLoopResult 構造体。

例外

body 引数が null です。

すべてのスレッドでスローされたすべての個別の例外を含む例外。

注釈

デリゲートは body 、イテレーション範囲内fromInclusiveの値 (、 toExclusive) ごとに 1 回呼び出されます。 これは、反復回数 (Int64) と ParallelLoopState 、ループの途中から抜け出すために使用できるインスタンスというパラメーターを使用して提供されます。

メソッドを Break 呼び出すと、現在の for メソッドの後のイテレーションは実行する必要はなく、現在のイテレーションより前のすべてのイテレーションが実行されることを操作に通知します。

したがって、Break を呼び出すことは、C# のような言語で従来 for のループ内で中断操作を使用するのと似ていますが、完全な代替ではありません。たとえば、現在のループの後のイテレーションが確実に実行されないという保証はありません。

現在のイテレーションの前にすべてのイテレーションを実行する必要がない場合は、 を使用する代わりに メソッドを Stop 使用 Breakします。 を呼び出 Stop すと、必要なすべての作業が既に完了しているため、現在のイテレーションの前か後かに関係なく、残りのすべてのイテレーションが破棄される可能性があることをループに通知 for します。 ただし、 と Break同様に、他のイテレーションが実行されない保証はありません。

ループが途中で終了した場合、 ParallelLoopResult 返される構造体にはループの完了に関する関連情報が含まれます。

が 以上toExclusiveの場合fromInclusive、メソッドはイテレーションを実行せずに直ちに を返します。

こちらもご覧ください

適用対象

For(Int64, Int64, Action<Int64>)

反復処理が並列で実行される可能性のある、64 ビットのインデックスを持つ for ループを実行します。

public:
 static System::Threading::Tasks::ParallelLoopResult For(long fromInclusive, long toExclusive, Action<long> ^ body);
public static System.Threading.Tasks.ParallelLoopResult For (long fromInclusive, long toExclusive, Action<long> body);
static member For : int64 * int64 * Action<int64> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function For (fromInclusive As Long, toExclusive As Long, body As Action(Of Long)) As ParallelLoopResult

パラメーター

fromInclusive
Int64

開始インデックス。ここで指定したインデックスから処理が開始されます。

toExclusive
Int64

終了インデックス。ここで指定したインデックスの前のインデックスまで処理が行われます。

body
Action<Int64>

1 回のイテレーションにつき 1 回呼び出されるデリゲート。

戻り値

完了したループの部分に関する情報を格納している構造。

例外

body 引数が null です。

すべてのスレッドでスローされたすべての個別の例外を含む例外。

注釈

デリゲートは body 、イテレーション範囲内fromInclusiveの値 (、 toExclusive) ごとに 1 回呼び出されます。 これは、反復カウント (Int64) をパラメーターとして指定します。

が 以上toExclusiveの場合fromInclusive、メソッドはイテレーションを実行せずにすぐにを返します。

こちらもご覧ください

適用対象

For(Int32, Int32, ParallelOptions, Action<Int32,ParallelLoopState>)

反復処理が並列で実行される可能性があり、ループ オプションを構成でき、ループの状態を監視および操作できる for ループを実行します。

public:
 static System::Threading::Tasks::ParallelLoopResult For(int fromInclusive, int toExclusive, System::Threading::Tasks::ParallelOptions ^ parallelOptions, Action<int, System::Threading::Tasks::ParallelLoopState ^> ^ body);
public static System.Threading.Tasks.ParallelLoopResult For (int fromInclusive, int toExclusive, System.Threading.Tasks.ParallelOptions parallelOptions, Action<int,System.Threading.Tasks.ParallelLoopState> body);
static member For : int * int * System.Threading.Tasks.ParallelOptions * Action<int, System.Threading.Tasks.ParallelLoopState> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function For (fromInclusive As Integer, toExclusive As Integer, parallelOptions As ParallelOptions, body As Action(Of Integer, ParallelLoopState)) As ParallelLoopResult

パラメーター

fromInclusive
Int32

開始インデックス。ここで指定したインデックスから処理が開始されます。

toExclusive
Int32

終了インデックス。ここで指定したインデックスの前のインデックスまで処理が行われます。

parallelOptions
ParallelOptions

この操作の動作を構成するオブジェクト。

body
Action<Int32,ParallelLoopState>

1 回のイテレーションにつき 1 回呼び出されるデリゲート。

戻り値

完了したループの部分に関する情報を格納している構造。

例外

parallelOptions 引数の CancellationToken が取り消されました。

body 引数が null です。

- または -

parallelOptions 引数が null です。

すべてのスレッドでスローされたすべての個別の例外を含む例外。

parallelOptions 内の CancellationTokenSource に関連付けられている CancellationToken は破棄されました。

注釈

デリゲートは body 、イテレーション範囲内fromInclusiveの値 (、 toExclusive) ごとに 1 回呼び出されます。 これは、反復回数 (Int32) と ParallelLoopState 、ループの途中から抜け出すために使用できるインスタンスというパラメーターを使用して提供されます。

が 以上toExclusiveの場合fromInclusive、メソッドはイテレーションを実行せずにすぐにを返します。

こちらもご覧ください

適用対象

For(Int32, Int32, ParallelOptions, Action<Int32>)

反復処理が並列で実行される可能性があり、ループ オプションを構成できる for ループを実行します。

public:
 static System::Threading::Tasks::ParallelLoopResult For(int fromInclusive, int toExclusive, System::Threading::Tasks::ParallelOptions ^ parallelOptions, Action<int> ^ body);
public static System.Threading.Tasks.ParallelLoopResult For (int fromInclusive, int toExclusive, System.Threading.Tasks.ParallelOptions parallelOptions, Action<int> body);
static member For : int * int * System.Threading.Tasks.ParallelOptions * Action<int> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function For (fromInclusive As Integer, toExclusive As Integer, parallelOptions As ParallelOptions, body As Action(Of Integer)) As ParallelLoopResult

パラメーター

fromInclusive
Int32

開始インデックス。ここで指定したインデックスから処理が開始されます。

toExclusive
Int32

終了インデックス。ここで指定したインデックスの前のインデックスまで処理が行われます。

parallelOptions
ParallelOptions

この操作の動作を構成するオブジェクト。

body
Action<Int32>

1 回のイテレーションにつき 1 回呼び出されるデリゲート。

戻り値

完了したループの部分に関する情報を格納している構造。

例外

parallelOptions 引数の CancellationToken が取り消されました。

body 引数が null です。

- または -

parallelOptions 引数が null です。

すべてのスレッドでスローされたすべての個別の例外を含む例外。

parallelOptions 内の CancellationTokenSource に関連付けられている CancellationToken は破棄されました。

次の例は、並列ループを取り消す方法を示しています。

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

class ParallelForCancellation
{
    // Demonstrated features:
    //		CancellationTokenSource
    // 		Parallel.For()
    //		ParallelOptions
    //		ParallelLoopResult
    // Expected results:
    // 		An iteration for each argument value (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) is executed.
    //		The order of execution of the iterations is undefined.
    //		The iteration when i=2 cancels the loop.
    //		Some iterations may bail out or not start at all; because they are temporally executed in unpredictable order, 
    //          it is impossible to say which will start/complete and which won't.
    //		At the end, an OperationCancelledException is surfaced.
    // Documentation:
    //		http://msdn.microsoft.com/library/system.threading.cancellationtokensource(VS.100).aspx
    static void CancelDemo()
    {
        CancellationTokenSource cancellationSource = new CancellationTokenSource();
        ParallelOptions options = new ParallelOptions();
        options.CancellationToken = cancellationSource.Token;

        try
        {
            ParallelLoopResult loopResult = Parallel.For(
                    0,
                    10,
                    options,
                    (i, loopState) =>
                    {
                        Console.WriteLine("Start Thread={0}, i={1}", Thread.CurrentThread.ManagedThreadId, i);

                        // Simulate a cancellation of the loop when i=2
                        if (i == 2)
                        {
                            cancellationSource.Cancel();
                        }

                        // Simulates a long execution
                        for (int j = 0; j < 10; j++)
                        {
                            Thread.Sleep(1 * 200);

                            // check to see whether or not to continue
                            if (loopState.ShouldExitCurrentIteration) return;
                        }

                        Console.WriteLine("Finish Thread={0}, i={1}", Thread.CurrentThread.ManagedThreadId, i);
                    }
                );

            if (loopResult.IsCompleted)
            {
                Console.WriteLine("All iterations completed successfully. THIS WAS NOT EXPECTED.");
            }
        }
        // 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.For has thrown an AggregateException. THIS WAS NOT EXPECTED.\n{0}", e);
        }
        // Catching the cancellation exception
        catch (OperationCanceledException e)
        {
            Console.WriteLine("An iteration has triggered a cancellation. THIS WAS EXPECTED.\n{0}", e.ToString());
        }
        finally
        {
           cancellationSource.Dispose();
        }
    }
}
Imports System.Threading
Imports System.Threading.Tasks

Module LoopCancellation
    ' Demonstrated features:
    '   CancellationTokenSource
    '   Parallel.For()
    '   ParallelOptions
    '   ParallelLoopResult
    ' Expected results:
    '   An iteration for each argument value (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) is executed.
    '   The order of execution of the iterations is undefined.
    '   The iteration when i=2 cancels the loop.
    '   Some iterations may bail out or not start at all; because they are temporally executed in unpredictable order, 
    '      it is impossible to say which will start/complete and which won't.
    '   At the end, an OperationCancelledException is surfaced.
    ' Documentation:
    '   http://msdn.microsoft.com/library/system.threading.cancellationtokensource(VS.100).aspx
    Private Sub Main()
        Dim cancellationSource As New CancellationTokenSource()
        Dim options As New ParallelOptions()
        options.CancellationToken = cancellationSource.Token

        Try
            Dim loopResult As ParallelLoopResult = _
                Parallel.For(0, 10, options, Sub(i, loopState)
                                                 Console.WriteLine("Start Thread={0}, i={1}", Thread.CurrentThread.ManagedThreadId, i)

                                                 ' Simulate a cancellation of the loop when i=2
                                                 If i = 2 Then
                                                     cancellationSource.Cancel()
                                                 End If

                                                 ' Simulates a long execution
                                                 For j As Integer = 0 To 9
                                                     Thread.Sleep(1 * 200)

                                                     ' check to see whether or not to continue
                                                     If loopState.ShouldExitCurrentIteration Then
                                                         Exit Sub
                                                     End If
                                                 Next

                                                 Console.WriteLine("Finish Thread={0}, i={1}", Thread.CurrentThread.ManagedThreadId, i)
                                             End Sub)

            If loopResult.IsCompleted Then
                Console.WriteLine("All iterations completed successfully. THIS WAS NOT EXPECTED.")
            End If
        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("An action has thrown an AggregateException. THIS WAS NOT EXPECTED." & vbLf & "{0}", e)
        Catch e As OperationCanceledException
            ' Catching the cancellation exception
            Console.WriteLine("An iteration has triggered a cancellation. THIS WAS EXPECTED." & vbLf & "{0}", e)
        Finally
            cancellationSource.Dispose()
        End Try
    End Sub
End Module

注釈

デリゲートは body 、イテレーション範囲内fromInclusiveの値 (、 toExclusive) ごとに 1 回呼び出されます。 これは、反復カウント (Int32) をパラメーターとして指定します。

が 以上toExclusiveの場合fromInclusive、メソッドはイテレーションを実行せずに直ちに を返します。

こちらもご覧ください

適用対象

For(Int64, Int64, ParallelOptions, Action<Int64,ParallelLoopState>)

反復処理が並列で実行される可能性があり、ループ オプションを構成でき、ループの状態を監視および操作できる、64 ビットのインデックスを持つ for ループを実行します。

public:
 static System::Threading::Tasks::ParallelLoopResult For(long fromInclusive, long toExclusive, System::Threading::Tasks::ParallelOptions ^ parallelOptions, Action<long, System::Threading::Tasks::ParallelLoopState ^> ^ body);
public static System.Threading.Tasks.ParallelLoopResult For (long fromInclusive, long toExclusive, System.Threading.Tasks.ParallelOptions parallelOptions, Action<long,System.Threading.Tasks.ParallelLoopState> body);
static member For : int64 * int64 * System.Threading.Tasks.ParallelOptions * Action<int64, System.Threading.Tasks.ParallelLoopState> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function For (fromInclusive As Long, toExclusive As Long, parallelOptions As ParallelOptions, body As Action(Of Long, ParallelLoopState)) As ParallelLoopResult

パラメーター

fromInclusive
Int64

開始インデックス。ここで指定したインデックスから処理が開始されます。

toExclusive
Int64

終了インデックス。ここで指定したインデックスの前のインデックスまで処理が行われます。

parallelOptions
ParallelOptions

この操作の動作を構成するオブジェクト。

body
Action<Int64,ParallelLoopState>

1 回のイテレーションにつき 1 回呼び出されるデリゲート。

戻り値

完了したループの部分に関する情報を格納している構造。

例外

parallelOptions 引数の CancellationToken が取り消されました。

body 引数が null です。

- または -

parallelOptions 引数が null です。

すべてのスレッドでスローされたすべての個別の例外を含む例外。

parallelOptions 内の CancellationTokenSource に関連付けられている CancellationToken は破棄されました。

次の例は、 オブジェクトで メソッドを Parallel.For 使用する方法を ParallelOptions 示しています。

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

class ParallelOptionsDemo
{
    // Demonstrated features:
    // 		Parallel.For()
    //		ParallelOptions
    // Expected results:
    // 		An iteration for each argument value (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) is executed.
    //		The order of execution of the iterations is undefined.
    //		Verify that no more than two threads have been used for the iterations.
    // Documentation:
    //		http://msdn.microsoft.com/library/system.threading.tasks.parallel.for(VS.100).aspx
    static void Main()
    {
        ParallelOptions options = new ParallelOptions();
        options.MaxDegreeOfParallelism = 2; // -1 is for unlimited. 1 is for sequential.

        try
        {
            Parallel.For(
                    0,
                    9,
                    options,
                    (i) =>
                    {
                        Console.WriteLine("Thread={0}, i={1}", Thread.CurrentThread.ManagedThreadId, i);
                    }
                );
        }
        // 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.For has thrown the following (unexpected) exception:\n{0}", e);
        }
    }
}
Imports System.Threading
Imports System.Threading.Tasks


Module ParallelForDemo

    ' Demonstrated features:
    '   Parallel.For()
    '   ParallelOptions
    ' Expected results:
    '   An iteration for each argument value (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) is executed.
    '   The order of execution of the iterations is undefined.
    '   Verify that no more than two threads have been used for the iterations.
    ' Documentation:
    '   http://msdn.microsoft.com/library/system.threading.tasks.parallel.for(VS.100).aspx
    Sub Main()
        Dim options As New ParallelOptions()
        options.MaxDegreeOfParallelism = 2 ' -1 is for unlimited. 1 is for sequential.
        Try
            Parallel.For(0, 9, options, Sub(i)
                                            Console.WriteLine("Thread={0}, i={1}", Thread.CurrentThread.ManagedThreadId, i)

                                        End Sub)
        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.For has thrown the following (unexpected) exception:" & vbLf & "{0}", e)
        End Try
    End Sub

End Module

注釈

デリゲートは body 、イテレーション範囲内fromInclusiveの値 (、 toExclusive) ごとに 1 回呼び出されます。 これは、反復回数 (Int64) と ParallelLoopState 、ループの途中から抜け出すために使用できるインスタンスというパラメーターを使用して提供されます。

が 以上toExclusiveの場合fromInclusive、メソッドはイテレーションを実行せずにすぐにを返します。

こちらもご覧ください

適用対象

For(Int64, Int64, ParallelOptions, Action<Int64>)

イテレーションが並列で実行される可能性があり、ループ オプションを構成できる、64 ビットのインデックスを持つ for ループを実行します。

public:
 static System::Threading::Tasks::ParallelLoopResult For(long fromInclusive, long toExclusive, System::Threading::Tasks::ParallelOptions ^ parallelOptions, Action<long> ^ body);
public static System.Threading.Tasks.ParallelLoopResult For (long fromInclusive, long toExclusive, System.Threading.Tasks.ParallelOptions parallelOptions, Action<long> body);
static member For : int64 * int64 * System.Threading.Tasks.ParallelOptions * Action<int64> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function For (fromInclusive As Long, toExclusive As Long, parallelOptions As ParallelOptions, body As Action(Of Long)) As ParallelLoopResult

パラメーター

fromInclusive
Int64

開始インデックス。ここで指定したインデックスから処理が開始されます。

toExclusive
Int64

終了インデックス。ここで指定したインデックスの前のインデックスまで処理が行われます。

parallelOptions
ParallelOptions

この操作の動作を構成するオブジェクト。

body
Action<Int64>

1 回のイテレーションにつき 1 回呼び出されるデリゲート。

戻り値

完了したループの部分に関する情報を格納している構造。

例外

parallelOptions 引数の CancellationToken が取り消されました。

body 引数が null です。

- または -

parallelOptions 引数が null です。

すべてのスレッドでスローされたすべての個別の例外を含む例外。

parallelOptions 内の CancellationTokenSource に関連付けられている CancellationToken は破棄されました。

次の例は、 を使用 ParallelOptions してカスタム タスク スケジューラを指定する方法を示しています。

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:
        //		http://msdn.microsoft.com/library/system.threading.tasks.taskscheduler(VS.100).aspx
        //		http://msdn.microsoft.com/library/dd997413(VS.100).aspx
        // More information:
        //		http://blogs.msdn.com/pfxteam/archive/2009/09/22/9898090.aspx
        static void Main()
        {
            ParallelOptions options = new ParallelOptions();

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

            try
            {
                Parallel.For(
                        0,
                        10,
                        options,
                        (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())
                        {
                            TryExecuteTask(task);
                        }
                    });

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

            // This method is invoked by the runtime to schedule a task
            protected override void QueueTask(Task task)
            {
                _tasks.Add(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)
                {
                    _tasks.CompleteAdding();

                    for (int i = 0; i < _n; i++)
                    {
                        _threads[i].Join();
                        _threads[i] = null;
                    }
                    _threads = null;
                    _tasks.Dispose();
                    _tasks = null;
                }
            }
    }
}
Imports System.Collections.Concurrent
Imports System.Threading
Imports System.Threading.Tasks

Module SchedulerDemo
    ' 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.
    '   A task is internally created for each thread of the task scheduler (plus an aditional internal task).
    '	Thus a scheduler thread may execute multiple iterations.
    ' Documentation:
    '   http://msdn.microsoft.com/library/system.threading.tasks.taskscheduler(VS.100).aspx
    '   http://msdn.microsoft.com/library/dd997413(VS.100).aspx
    ' More information:
    '   http://blogs.msdn.com/pfxteam/archive/2009/09/22/9898090.aspx
    Sub Main()
        Dim options As New ParallelOptions()

        ' Construct and associate a custom task scheduler
        options.TaskScheduler = New TwoThreadTaskScheduler()

        Try
            Parallel.For(0, 10, options, Sub(i, localState)
                                             Console.WriteLine("i={0}, Task={1}, Thread={2}", i, Task.CurrentId, Thread.CurrentThread.ManagedThreadId)

                                         End Sub)
        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("An iteration has thrown an exception. THIS WAS NOT EXPECTED." & vbLf & "{0}", e)
        End Try
    End Sub

    ' This scheduler schedules all tasks on (at most) two threads
    Private NotInheritable Class TwoThreadTaskScheduler
        Inherits TaskScheduler
        Implements 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 _tasks As New BlockingCollection(Of Task)()

        ' Maintain an array of threads. (Feel free to bump up _n.)
        Private ReadOnly _n As Integer = 2
        Private _threads As Thread()

        Public Sub New()
            _threads = New Thread(_n - 1) {}

            ' Create unstarted threads based on the same inline delegate
            For i As Integer = 0 To _n - 1
                _threads(i) = New Thread(Sub()
                                             ' The following loop blocks until items become available in the blocking collection.
                                             ' Then one thread is unblocked to consume that item.
                                             For Each task In _tasks.GetConsumingEnumerable()
                                                 TryExecuteTask(task)
                                             Next
                                         End Sub)

                ' Start each thread
                _threads(i).IsBackground = True
                _threads(i).Start()
            Next
        End Sub

        ' This method is invoked by the runtime to schedule a task
        Protected Overloads Overrides Sub QueueTask(ByVal task As Task)
            _tasks.Add(task)
        End Sub

        ' 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 Overloads Overrides Function TryExecuteTaskInline(ByVal task As Task, ByVal taskWasPreviouslyQueued As Boolean) As Boolean
            Return False
        End Function

        Public Overloads Overrides ReadOnly Property MaximumConcurrencyLevel() As Integer
            Get
                Return _n
            End Get
        End Property

        Protected Overloads Overrides Function GetScheduledTasks() As IEnumerable(Of Task)
            Return _tasks.ToArray()
        End Function

        ' 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 Sub Dispose() Implements IDisposable.Dispose
            If _threads IsNot Nothing Then
                _tasks.CompleteAdding()

                For i As Integer = 0 To _n - 1
                    _threads(i).Join()
                    _threads(i) = Nothing
                Next
                _threads = Nothing
                _tasks.Dispose()
                _tasks = Nothing
            End If
        End Sub
    End Class

End Module

注釈

64 ビット インデックスをサポートします。 デリゲートは body 、イテレーション範囲内fromInclusiveの値 (、 toExclusive) ごとに 1 回呼び出されます。 これは、反復カウント (Int64) をパラメーターとして指定します。

が 以上toExclusiveの場合fromInclusive、メソッドはイテレーションを実行せずに直ちに を返します。

こちらもご覧ください

適用対象

For<TLocal>(Int32, Int32, Func<TLocal>, Func<Int32,ParallelLoopState,TLocal,TLocal>, Action<TLocal>)

反復処理が並列で実行される可能性があり、ループの状態を監視および操作できる、スレッド ローカル データを持つ for ループを実行します。

public:
generic <typename TLocal>
 static System::Threading::Tasks::ParallelLoopResult For(int fromInclusive, int toExclusive, Func<TLocal> ^ localInit, Func<int, System::Threading::Tasks::ParallelLoopState ^, TLocal, TLocal> ^ body, Action<TLocal> ^ localFinally);
public static System.Threading.Tasks.ParallelLoopResult For<TLocal> (int fromInclusive, int toExclusive, Func<TLocal> localInit, Func<int,System.Threading.Tasks.ParallelLoopState,TLocal,TLocal> body, Action<TLocal> localFinally);
static member For : int * int * Func<'Local> * Func<int, System.Threading.Tasks.ParallelLoopState, 'Local, 'Local> * Action<'Local> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function For(Of TLocal) (fromInclusive As Integer, toExclusive As Integer, localInit As Func(Of TLocal), body As Func(Of Integer, ParallelLoopState, TLocal, TLocal), localFinally As Action(Of TLocal)) As ParallelLoopResult

型パラメーター

TLocal

スレッド ローカル データの型。

パラメーター

fromInclusive
Int32

開始インデックス。ここで指定したインデックスから処理が開始されます。

toExclusive
Int32

終了インデックス。ここで指定したインデックスの前のインデックスまで処理が行われます。

localInit
Func<TLocal>

各タスクのローカル データの初期状態を返す関数デリゲート。

body
Func<Int32,ParallelLoopState,TLocal,TLocal>

1 回のイテレーションにつき 1 回呼び出されるデリゲート。

localFinally
Action<TLocal>

各タスクのローカル状態に対して最後の操作を行うデリゲート。

戻り値

完了したループの部分に関する情報を格納している構造。

例外

body 引数が null です。

- または -

localInit 引数が null です。

- または -

localFinally 引数が null です。

すべてのスレッドでスローされたすべての個別の例外を含む例外。

注釈

デリゲートは body 、イテレーション範囲内fromInclusiveの値 (、 toExclusive) ごとに 1 回呼び出されます。 このパラメーターには、繰り返し回数 (Int32) ParallelLoopState 、途中でループから抜け出すために使用できるインスタンス、および同じスレッドで実行されるイテレーション間で共有されるローカル状態が含まれます。

デリゲートは localInit 、ループの実行に参加するタスクごとに 1 回呼び出され、それらの各タスクの初期ローカル状態を返します。 これらの初期状態は、各タスクの最初 body の呼び出しに渡されます。 次に、後続のすべての本文呼び出しで、次の本文呼び出しに渡される変更された可能性のある状態値が返されます。 最後に、各タスクの最後の本文呼び出しは、デリゲートに渡される状態値を localFinally 返します。 デリゲートは localFinally 、各タスクのローカル状態に対して最終的なアクションを実行するために、タスクごとに 1 回呼び出されます。 このデリゲートは、複数のタスクで同時に呼び出される場合があります。そのため、すべての共有変数へのアクセスを同期する必要があります。

メソッドは Parallel.For 、既存のタスクが完了し、新しいタスクに置き換えられるので、実行の有効期間中にスレッドよりも多くのタスクを使用する場合があります。 これにより、基になる TaskScheduler オブジェクトは、ループを処理するスレッドを追加、変更、または削除できます。

が 以上toExclusiveの場合fromInclusive、メソッドはイテレーションを実行せずに直ちに を返します。

このメソッドを使用する例については、「 方法: Thread-Local 変数を使用して Parallel.For ループを記述する」を参照してください。

こちらもご覧ください

適用対象

For<TLocal>(Int64, Int64, Func<TLocal>, Func<Int64,ParallelLoopState,TLocal,TLocal>, Action<TLocal>)

反復処理が並列で実行される可能性があり、ループの状態を監視および操作できる、64 ビットのインデックスとスレッド ローカル データを持つ for ループを実行します。

public:
generic <typename TLocal>
 static System::Threading::Tasks::ParallelLoopResult For(long fromInclusive, long toExclusive, Func<TLocal> ^ localInit, Func<long, System::Threading::Tasks::ParallelLoopState ^, TLocal, TLocal> ^ body, Action<TLocal> ^ localFinally);
public static System.Threading.Tasks.ParallelLoopResult For<TLocal> (long fromInclusive, long toExclusive, Func<TLocal> localInit, Func<long,System.Threading.Tasks.ParallelLoopState,TLocal,TLocal> body, Action<TLocal> localFinally);
static member For : int64 * int64 * Func<'Local> * Func<int64, System.Threading.Tasks.ParallelLoopState, 'Local, 'Local> * Action<'Local> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function For(Of TLocal) (fromInclusive As Long, toExclusive As Long, localInit As Func(Of TLocal), body As Func(Of Long, ParallelLoopState, TLocal, TLocal), localFinally As Action(Of TLocal)) As ParallelLoopResult

型パラメーター

TLocal

スレッド ローカル データの型。

パラメーター

fromInclusive
Int64

開始インデックス。ここで指定したインデックスから処理が開始されます。

toExclusive
Int64

終了インデックス。ここで指定したインデックスの前のインデックスまで処理が行われます。

localInit
Func<TLocal>

各タスクのローカル データの初期状態を返す関数デリゲート。

body
Func<Int64,ParallelLoopState,TLocal,TLocal>

1 回のイテレーションにつき 1 回呼び出されるデリゲート。

localFinally
Action<TLocal>

各タスクのローカル状態に対して最後の操作を行うデリゲート。

戻り値

完了したループの部分に関する情報を格納している構造。

例外

body 引数が null です。

- または -

localInit 引数が null です。

- または -

localFinally 引数が null です。

すべてのスレッドでスローされたすべての個別の例外を含む例外。

注釈

デリゲートは body 、イテレーション範囲内fromInclusiveの値 (、 toExclusive) ごとに 1 回呼び出されます。 このパラメーターには、繰り返し回数 (Int64) ParallelLoopState 、ループの途中から抜け出すために使用できるインスタンス、および同じタスクで実行されるイテレーション間で共有されるローカル状態が含まれます。

デリゲートは localInit 、ループの実行に参加するタスクごとに 1 回呼び出され、それらの各タスクの初期ローカル状態を返します。 これらの初期状態は、各タスクの最初 body の呼び出しに渡されます。 次に、後続のすべての本文呼び出しで、次の本文呼び出しに渡される変更された可能性のある状態値が返されます。 最後に、各タスクの最後の本文呼び出しは、デリゲートに渡される状態値を localFinally 返します。 デリゲートは localFinally 、各タスクのローカル状態に対して最終的なアクションを実行するために、タスクごとに 1 回呼び出されます。 このデリゲートは、複数のタスクで同時に呼び出される場合があります。そのため、すべての共有変数へのアクセスを同期する必要があります。

メソッドは Parallel.For 、既存のタスクが完了し、新しいタスクに置き換えられるので、実行の有効期間中にスレッドよりも多くのタスクを使用する場合があります。 これにより、基になる TaskScheduler オブジェクトは、ループを処理するスレッドを追加、変更、または削除できます。

が 以上toExclusiveの場合fromInclusive、メソッドはイテレーションを実行せずに直ちに を返します。

このメソッドを使用する例については、「 方法: Thread-Local 変数を使用して Parallel.For ループを記述する」を参照してください。

こちらもご覧ください

適用対象

For<TLocal>(Int32, Int32, ParallelOptions, Func<TLocal>, Func<Int32,ParallelLoopState,TLocal,TLocal>, Action<TLocal>)

反復処理が並列で実行される可能性があり、ループ オプションを構成でき、ループの状態を監視および操作できる、スレッド ローカル データを持つ for ループを実行します。

public:
generic <typename TLocal>
 static System::Threading::Tasks::ParallelLoopResult For(int fromInclusive, int toExclusive, System::Threading::Tasks::ParallelOptions ^ parallelOptions, Func<TLocal> ^ localInit, Func<int, System::Threading::Tasks::ParallelLoopState ^, TLocal, TLocal> ^ body, Action<TLocal> ^ localFinally);
public static System.Threading.Tasks.ParallelLoopResult For<TLocal> (int fromInclusive, int toExclusive, System.Threading.Tasks.ParallelOptions parallelOptions, Func<TLocal> localInit, Func<int,System.Threading.Tasks.ParallelLoopState,TLocal,TLocal> body, Action<TLocal> localFinally);
static member For : int * int * System.Threading.Tasks.ParallelOptions * Func<'Local> * Func<int, System.Threading.Tasks.ParallelLoopState, 'Local, 'Local> * Action<'Local> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function For(Of TLocal) (fromInclusive As Integer, toExclusive As Integer, parallelOptions As ParallelOptions, localInit As Func(Of TLocal), body As Func(Of Integer, ParallelLoopState, TLocal, TLocal), localFinally As Action(Of TLocal)) As ParallelLoopResult

型パラメーター

TLocal

スレッド ローカル データの型。

パラメーター

fromInclusive
Int32

開始インデックス。ここで指定したインデックスから処理が開始されます。

toExclusive
Int32

終了インデックス。ここで指定したインデックスの前のインデックスまで処理が行われます。

parallelOptions
ParallelOptions

この操作の動作を構成するオブジェクト。

localInit
Func<TLocal>

各タスクのローカル データの初期状態を返す関数デリゲート。

body
Func<Int32,ParallelLoopState,TLocal,TLocal>

1 回のイテレーションにつき 1 回呼び出されるデリゲート。

localFinally
Action<TLocal>

各タスクのローカル状態に対して最後の操作を行うデリゲート。

戻り値

完了したループの部分に関する情報を格納している構造。

例外

body 引数が null です。

- または -

localInit 引数が null です。

- または -

localFinally 引数が null です。

- または -

parallelOptions 引数が null です。

parallelOptions 引数の CancellationToken が取り消されました。

parallelOptions 内の CancellationTokenSource に関連付けられている CancellationToken は破棄されました。

すべてのスレッドでスローされたすべての個別の例外を含む例外。

次の例では、スレッド ローカル変数を使用して、多くの長い操作の結果の合計を計算します。 次の使用例は、並列処理の次数を 4 に制限します。

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

class ThreadLocalForWithOptions
{
   // The number of parallel iterations to perform.
   const int N = 1000000;

   static void Main()
   {
      // The result of all thread-local computations.
      int result = 0;

      // This example limits the degree of parallelism to four.
      // You might limit the degree of parallelism when your algorithm
      // does not scale beyond a certain number of cores or when you 
      // enforce a particular quality of service in your application.

      Parallel.For(0, N, new ParallelOptions { MaxDegreeOfParallelism = 4 },
         // Initialize the local states
         () => 0,
         // Accumulate the thread-local computations in the loop body
         (i, loop, localState) =>
         {
            return localState + Compute(i);
         },
         // Combine all local states
         localState => Interlocked.Add(ref result, localState)
      );

      // Print the actual and expected results.
      Console.WriteLine("Actual result: {0}. Expected 1000000.", result);
   }

   // Simulates a lengthy operation.
   private static int Compute(int n)
   {
      for (int i = 0; i < 10000; i++) ;
      return 1;
   }
}
Imports System.Threading
Imports System.Threading.Tasks

Module ThreadLocalForWithOptions

   ' The number of parallel iterations to perform.
   Const N As Integer = 1000000

   Sub Main()
      ' The result of all thread-local computations.
      Dim result As Integer = 0

      ' This example limits the degree of parallelism to four.
      ' You might limit the degree of parallelism when your algorithm
      ' does not scale beyond a certain number of cores or when you 
      ' enforce a particular quality of service in your application.

      Parallel.For(0, N, New ParallelOptions With {.MaxDegreeOfParallelism = 4},
         Function()
            ' Initialize the local states 
            Return 0
         End Function,
         Function(i, loopState, localState)
            ' Accumulate the thread-local computations in the loop body
            Return localState + Compute(i)
         End Function,
         Sub(localState)
            ' Combine all local states
            Interlocked.Add(result, localState)
         End Sub
      )

      ' Print the actual and expected results.
      Console.WriteLine("Actual result: {0}. Expected 1000000.", result)
   End Sub

   ' Simulates a lengthy operation.
   Function Compute(ByVal n As Integer) As Integer
      For i As Integer = 0 To 10000
      Next
      Return 1
   End Function
End Module

注釈

デリゲートは body 、イテレーション範囲内fromInclusiveの値 (、 toExclusive) ごとに 1 回呼び出されます。 このパラメーターには、繰り返し回数 (Int32) ParallelLoopState 、ループの途中から抜け出すために使用できるインスタンス、および同じタスクで実行されるイテレーション間で共有されるローカル状態が含まれます。

デリゲートは localInit 、ループの実行に参加するタスクごとに 1 回呼び出され、それらの各タスクの初期ローカル状態を返します。 これらの初期状態は、各タスクの最初 body の呼び出しに渡されます。 次に、後続のすべての本文呼び出しで、次の本文呼び出しに渡される変更された可能性のある状態値が返されます。 最後に、各タスクの最後の本文呼び出しは、デリゲートに渡される状態値を localFinally 返します。 デリゲートは localFinally 、各タスクのローカル状態に対して最終的なアクションを実行するために、タスクごとに 1 回呼び出されます。 このデリゲートは、複数のスレッドで同時に呼び出される場合があります。そのため、すべての共有変数へのアクセスを同期する必要があります。

メソッドは Parallel.For 、既存のタスクが完了し、新しいタスクに置き換えられるので、実行の有効期間中にスレッドよりも多くのタスクを使用する場合があります。 これにより、基になる TaskScheduler オブジェクトは、ループを処理するスレッドを追加、変更、または削除できます。

が 以上toExclusiveの場合fromInclusive、メソッドはイテレーションを実行せずに直ちに を返します。

こちらもご覧ください

適用対象

For<TLocal>(Int64, Int64, ParallelOptions, Func<TLocal>, Func<Int64,ParallelLoopState,TLocal,TLocal>, Action<TLocal>)

反復処理が並列で実行される可能性があり、ループ オプションを構成でき、ループの状態を監視および操作できる、64 ビットのインデックスとスレッド ローカル データを持つ for ループを実行します。

public:
generic <typename TLocal>
 static System::Threading::Tasks::ParallelLoopResult For(long fromInclusive, long toExclusive, System::Threading::Tasks::ParallelOptions ^ parallelOptions, Func<TLocal> ^ localInit, Func<long, System::Threading::Tasks::ParallelLoopState ^, TLocal, TLocal> ^ body, Action<TLocal> ^ localFinally);
public static System.Threading.Tasks.ParallelLoopResult For<TLocal> (long fromInclusive, long toExclusive, System.Threading.Tasks.ParallelOptions parallelOptions, Func<TLocal> localInit, Func<long,System.Threading.Tasks.ParallelLoopState,TLocal,TLocal> body, Action<TLocal> localFinally);
static member For : int64 * int64 * System.Threading.Tasks.ParallelOptions * Func<'Local> * Func<int64, System.Threading.Tasks.ParallelLoopState, 'Local, 'Local> * Action<'Local> -> System.Threading.Tasks.ParallelLoopResult
Public Shared Function For(Of TLocal) (fromInclusive As Long, toExclusive As Long, parallelOptions As ParallelOptions, localInit As Func(Of TLocal), body As Func(Of Long, ParallelLoopState, TLocal, TLocal), localFinally As Action(Of TLocal)) As ParallelLoopResult

型パラメーター

TLocal

スレッド ローカル データの型。

パラメーター

fromInclusive
Int64

開始インデックス。ここで指定したインデックスから処理が開始されます。

toExclusive
Int64

終了インデックス。ここで指定したインデックスの前のインデックスまで処理が行われます。

parallelOptions
ParallelOptions

この操作の動作を構成するオブジェクト。

localInit
Func<TLocal>

各スレッドのローカル データの初期状態を返す関数デリゲート。

body
Func<Int64,ParallelLoopState,TLocal,TLocal>

1 回のイテレーションにつき 1 回呼び出されるデリゲート。

localFinally
Action<TLocal>

各スレッドのローカル状態に対して最後の操作を行うデリゲート。

戻り値

完了したループの部分に関する情報を格納している構造。

例外

body 引数が null です。

- または -

localInit 引数が null です。

- または -

localFinally 引数が null です。

- または -

parallelOptions 引数が null です。

parallelOptions 引数の CancellationToken が取り消されました。

parallelOptions 内の CancellationTokenSource に関連付けられている CancellationToken は破棄されました。

すべてのスレッドでスローされたすべての個別の例外を含む例外。

注釈

デリゲートは body 、イテレーション範囲内fromInclusiveの値 (、 toExclusive) ごとに 1 回呼び出されます。 このパラメーターには、繰り返し回数 (Int64) ParallelLoopState 、途中でループから抜け出すために使用できるインスタンス、および同じスレッドで実行されるイテレーション間で共有されるローカル状態が含まれます。

デリゲートは localInit 、ループの実行に参加するスレッドごとに 1 回呼び出され、それらの各スレッドの初期ローカル状態を返します。 これらの初期状態は、各スレッドの最初 body の呼び出しに渡されます。 次に、後続のすべての本文呼び出しで、次の本文呼び出しに渡される変更された可能性のある状態値が返されます。 最後に、各スレッドの最後の本文呼び出しは、デリゲートに渡される状態値を localFinally 返します。 デリゲートは localFinally スレッドごとに 1 回呼び出され、各スレッドのローカル状態に対して最終的なアクションが実行されます。 このデリゲートは、複数のスレッドで同時に呼び出される場合があります。そのため、すべての共有変数へのアクセスを同期する必要があります。

メソッドは Parallel.For 、既存のタスクが完了し、新しいタスクに置き換えられるので、実行の有効期間中にスレッドよりも多くのタスクを使用する場合があります。 これにより、基になる TaskScheduler オブジェクトは、ループを処理するスレッドを追加、変更、または削除できます。

が 以上toExclusiveの場合fromInclusive、メソッドはイテレーションを実行せずに直ちに を返します。

こちらもご覧ください

適用対象