Parallel.For 메서드

정의

반복이 병렬로 실행될 수 있는 for 루프를 실행합니다.Executes a for loop in which iterations may run in parallel.

오버로드

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

반복을 병렬로 실행할 수 있고 루프 상태를 모니터링 및 조작할 수 있는 for 루프를 실행합니다.Executes a for loop in which iterations may run in parallel and the state of the loop can be monitored and manipulated.

For(Int32, Int32, Action<Int32>)

반복이 병렬로 실행될 수 있는 for 루프를 실행합니다.Executes a for loop in which iterations may run in parallel.

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

64비트 인덱스를 사용하여 반복을 병렬로 실행할 수 있고 루프 상태를 모니터링 및 조작할 수 있는 for 루프를 실행합니다.Executes a for loop with 64-bit indexes in which iterations may run in parallel and the state of the loop can be monitored and manipulated.

For(Int64, Int64, Action<Int64>)

64비트 인덱스를 사용하여 반복을 병렬로 실행할 수 있는 for 루프를 실행합니다.Executes a for loop with 64-bit indexes in which iterations may run in parallel.

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

반복을 병렬로 실행할 수 있고 루프 옵션을 구성할 수 있으며 루프 상태를 모니터링 및 조작할 수 있는 for 작업을 루프를 실행합니다.Executes a for loop in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated.

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

반복을 병렬로 실행할 수 있고 루프 옵션을 구성할 수 있는 for 루프를 실행합니다.Executes a for loop in which iterations may run in parallel and loop options can be configured.

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

64비트 인덱스를 사용하여 반복을 병렬로 실행할 수 있고 루프 옵션을 구성할 수 있으며 루프 상태를 모니터링 및 조작할 수 있는 for 루프를 실행합니다.Executes a for loop with 64-bit indexes in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated.

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

64비트 인덱스를 사용하여 반복을 병렬로 실행할 수 있고 루프 옵션을 구성할 수 있는 for 루프를 실행합니다.Executes a for loop with 64-bit indexes in which iterations may run in parallel and loop options can be configured.

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

64비트 인덱스와 스레드 로컬 데이터를 사용하여 반복을 병렬로 실행할 수 있고 루프 옵션을 구성할 수 있으며 루프 상태를 모니터링 및 조작할 수 있는 for 루프를 실행합니다.Executes a for loop with 64-bit indexes and thread-local data in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated.

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

스레드 로컬 데이터를 사용하여 반복을 병렬로 실행할 수 있고 루프 옵션을 구성할 수 있으며 루프 상태를 모니터링 및 조작할 수 있는 for 루프를 실행합니다.Executes a for loop with thread-local data in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated.

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

스레드 로컬 데이터를 사용하여 반복을 병렬로 실행할 수 있고 루프 상태를 모니터링 및 조작할 수 있는 for 루프를 실행합니다.Executes a for loop with thread-local data in which iterations may run in parallel, and the state of the loop can be monitored and manipulated.

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

64비트 인덱스와 스레드 로컬 데이터를 사용하여 반복을 병렬로 실행할 수 있고 루프 상태를 모니터링 및 조작할 수 있는 for 루프를 실행합니다.Executes a for loop with 64-bit indexes and thread-local data in which iterations may run in parallel, and the state of the loop can be monitored and manipulated.

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

반복을 병렬로 실행할 수 있고 루프 상태를 모니터링 및 조작할 수 있는 for 루프를 실행합니다.Executes a for loop in which iterations may run in parallel and the state of the loop can be monitored and manipulated.

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

시작 인덱스(포함)입니다.The start index, inclusive.

toExclusive
Int32

끝 인덱스(제외)입니다.The end index, exclusive.

body
Action<Int32,ParallelLoopState>

반복당 한 번씩 호출되는 대리자입니다.The delegate that is invoked once per iteration.

반환

완료된 루프의 부분에 대한 정보가 포함된 구조체입니다.A structure that contains information about which portion of the loop completed.

예외

body 인수가 null인 경우The body argument is null.

모든 스레드에서 throw 된 모든 개별 예외를 포함 하는 예외입니다.The exception that contains all the individual exceptions thrown on all threads.

예제

다음 예제에서는 동시에 최대 100 개의 루프 반복을 실행합니다.The following example executes up to 100 iterations of a loop in parallel. 1에서 1,000 밀리초 임의의 간격에 대 한 각 반복 일시 중지합니다.Each iteration pauses for a random interval from 1 to 1,000 milliseconds. 임의로 생성 된 값은 ParallelLoopState.Break 메서드가 호출 되는 루프의 반복을 결정 합니다.A randomly generated value determines on which iteration of the loop the ParallelLoopState.Break method is called. 예제의 출력에 표시 된 것 처럼, 해당 인덱스가 ParallelLoopState.LowestBreakIteration 속성 값 보다 큰 반복은 ParallelLoopState.Break 메서드를 호출한 후에 시작 되지 않습니다.As the output from the example shows, no iterations whose index is greater than the ParallelLoopState.LowestBreakIteration property value start after the call to the ParallelLoopState.Break method.

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);
      Nullable<long> lowest = new Nullable<long>();

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

      var result = Parallel.For(1, 101, (i, state) => {
                                            Console.WriteLine("Beginning iteration {0}", i);
                                            int delay;
                                            Monitor.Enter(rnd);
                                               delay = rnd.Next(1, 1001);
                                            Monitor.Exit(rnd);
                                            Thread.Sleep(delay);
                                            
                                            if (state.ShouldExitCurrentIteration) {
                                               if (state.LowestBreakIteration < i)
                                                  return;
                                            }

                                            if (i == breakIndex) {
                                               Console.WriteLine("Break in iteration {0}", i);
                                               state.Break();
                                               if (state.LowestBreakIteration.HasValue)
                                                  if (lowest < state.LowestBreakIteration)
                                                     lowest = state.LowestBreakIteration;
                                                  else
                                                     lowest = state.LowestBreakIteration;
                                            }

                                            Console.WriteLine("Completed iteration {0}", i);
                                       });
         if (lowest.HasValue)
            Console.WriteLine("\nLowest Break Iteration: {0}", lowest);
         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 메서드를 호출 했는지 여부를 확인 합니다.Because iterations of the loop are still likely to be executing when the ParallelLoopState.Break method is called, each iteration calls the ParallelLoopState.ShouldExitCurrentIteration property to check whether another iteration has called the ParallelLoopState.Break method. 속성 값이 true이면 반복에서 ParallelLoopState.LowestBreakIteration 속성의 값을 확인 하 고, 현재 반복의 인덱스 값 보다 크면를 즉시 반환 합니다.If the property value is true, the iteration checks the value of the ParallelLoopState.LowestBreakIteration property and, if it is greater than the current iteration's index value, returns immediately.

설명

body 대리자는 반복 범위 (fromInclusive, toExclusive)의 각 값에 대해 한 번씩 호출 됩니다.The body delegate is invoked once for each value in the iteration range (fromInclusive, toExclusive). 두 개의 인수를 사용 하 여 제공 됩니다.It is provided with two arguments:

  • 반복 횟수를 나타내는 Int32 값입니다.An Int32 value that represents the iteration count.

  • 루프를 중간에 중단 하는 데 사용할 수 있는 ParallelLoopState 인스턴스입니다.A ParallelLoopState instance that can be used to break out of the loop prematurely. ParallelLoopState 개체는 컴파일러에서 생성 됩니다. 사용자 코드에서 인스턴스화할 수 없습니다.The ParallelLoopState object is created by the compiler; it cannot be instantiated in user code.

Break 메서드를 호출 하면 현재 작업을 실행할 필요가 없는 후에 반복 되는 for 작업에 알립니다.Calling the Break method informs the for operation that iterations after the current one don't have to execute. 그러나 현재 모든 반복 하나 아직 아직 하지 않은 경우 실행 되어야 합니다.However, all iterations before the current one will still have to be executed if they haven't already.

따라서 Break를 호출 하는 것은와 같은 C#언어에서 기존 for 루프 내에서 중단 작업을 사용 하는 것과 유사 하지만 완벽 한 대체 방법은 아닙니다. 예를 들어 현재 항목 이후의 반복이 명확 하 게 실행 되지 않을 수 있습니다.Therefore, calling Break is similar to using a break operation within a conventional for loop in a language like C#, but it is not a perfect substitute: For example, there is no guarantee that iterations after the current one will definitely not execute.

현재 항목 이전에 모든 반복을 실행 해야 하는 경우에는 Break를 사용 하는 대신 Stop 메서드를 사용 합니다.If executing all iterations before the current one is not necessary, use the Stop method instead of using Break. Stop를 호출 하면 필요한 모든 작업이 이미 완료 되었으므로 현재 반복 전후에 있는지 여부에 관계 없이 나머지 반복을 모두 중단할 수 있음을 for 루프에 알립니다.Calling Stop informs the for loop that it may abandon all remaining iterations, regardless of whether they're before or after the current iteration, because all required work will have already been completed. 그러나 Break와 마찬가지로 다른 반복이 실행 되지 않는다는 보장이 없습니다.However, as with Break, there are no guarantees regarding which other iterations will not execute.

루프를 중간에 종료 한 경우 반환 되는 ParallelLoopResult 구조에는 루프의 완료에 대 한 관련 정보가 포함 됩니다.If a loop is ended prematurely, the ParallelLoopResult structure that is returned will contain relevant information about the loop's completion.

fromInclusivetoExclusive크거나 같으면 메서드가 반복을 수행 하지 않고 즉시 반환 됩니다.If fromInclusive is greater than or equal to toExclusive, the method returns immediately without performing any iterations.

추가 정보

For(Int32, Int32, Action<Int32>)

반복이 병렬로 실행될 수 있는 for 루프를 실행합니다.Executes a for loop in which iterations may run in parallel.

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

시작 인덱스(포함)입니다.The start index, inclusive.

toExclusive
Int32

끝 인덱스(제외)입니다.The end index, exclusive.

body
Action<Int32>

반복당 한 번씩 호출되는 대리자입니다.The delegate that is invoked once per iteration.

반환

완료된 루프 부분에 대한 정보가 포함된 구조체입니다.A structure that contains information about which portion of the loop completed.

예외

body 인수가 null인 경우The body argument is null.

모든 스레드에서 throw 된 모든 개별 예외를 포함 하는 예외입니다.The exception that contains all the individual exceptions thrown on all threads.

예제

다음 예제에서는 For 메서드를 사용 하 여 임의의 바이트 값을 생성 하 고 합계를 계산 하는 대리자의 100 호출을 수행 합니다.The following example uses the For method for 100 invocations of a delegate that generates random byte values and computes their sum.

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)의 각 값에 대해 한 번씩 호출 됩니다.The body delegate is invoked once for each value in the iteration range (fromInclusive, toExclusive). 반복 횟수 (Int32)가 매개 변수로 제공 됩니다.It is provided with the iteration count (Int32) as a parameter.

fromInclusivetoExclusive크거나 같으면 메서드가 반복을 수행 하지 않고 즉시 반환 됩니다.If fromInclusive is greater than or equal to toExclusive, the method returns immediately without performing any iterations.

추가 정보

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

64비트 인덱스를 사용하여 반복을 병렬로 실행할 수 있고 루프 상태를 모니터링 및 조작할 수 있는 for 루프를 실행합니다.Executes a for loop with 64-bit indexes in which iterations may run in parallel and the state of the loop can be monitored and manipulated.

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

시작 인덱스(포함)입니다.The start index, inclusive.

toExclusive
Int64

끝 인덱스(제외)입니다.The end index, exclusive.

body
Action<Int64,ParallelLoopState>

반복당 한 번씩 호출되는 대리자입니다.The delegate that is invoked once per iteration.

반환

완료된 루프의 부분에 대한 정보가 포함된 ParallelLoopResult 구조체입니다.A ParallelLoopResult structure that contains information on what portion of the loop completed.

예외

body 인수가 null인 경우The body argument is null.

모든 스레드에서 throw 된 모든 개별 예외를 포함 하는 예외입니다.The exception that contains all the individual exceptions thrown on all threads.

설명

body 대리자는 반복 범위 (fromInclusive, toExclusive)의 각 값에 대해 한 번씩 호출 됩니다.The body delegate is invoked once for each value in the iteration range (fromInclusive, toExclusive). 이 매개 변수는 반복 횟수 (Int64) 및 루프를 중간에 중단 하는 데 사용할 수 있는 ParallelLoopState 인스턴스와 같은 매개 변수를 제공 합니다.It is provided with the following parameters: the iteration count (Int64), and a ParallelLoopState instance that may be used to break out of the loop prematurely.

Break 메서드를 호출 하면 현재 작업을 실행할 필요 없이 반복 하는 for 작업에 대 한 알림이 수행 됩니다.Calling the Break method informs the for operation that iterations after the current one don't have to be executed, but all iterations before the current one do.

따라서 Break 호출은와 같은 C#언어에서 기존 for 루프 내에서 중단 작업을 사용 하는 것과 유사 하지만 완전 한 대체가 아닙니다. 예를 들어 현재 항목 이후의 반복이 명확 하 게 실행 되지 않을 수 있습니다.Therefore, calling Break is similar to using a break operation within a conventional for loop in a language like C#, but it is not a perfect substitute: For example, there is no guarantee that iterations after the current one will definitely not execute.

현재 항목 이전에 모든 반복을 실행 해야 하는 경우에는 Break를 사용 하는 대신 Stop 메서드를 사용 합니다.If executing all iterations before the current one is not necessary, use the Stop method instead of using Break. Stop를 호출 하면 필요한 모든 작업이 이미 완료 되었으므로 현재 반복 전후에 있는지 여부에 관계 없이 나머지 반복을 모두 중단할 수 있음을 for 루프에 알립니다.Calling Stop informs the for loop that it may abandon all remaining iterations, regardless of whether they're before or after the current iteration, because all required work will have already been completed. 그러나 Break와 마찬가지로 다른 반복이 실행 되지 않는다는 보장이 없습니다.However, as with Break, there are no guarantees regarding which other iterations will not execute.

루프를 중간에 종료 한 경우 반환 되는 ParallelLoopResult 구조에는 루프의 완료에 대 한 관련 정보가 포함 됩니다.If a loop is ended prematurely, the ParallelLoopResult structure that is returned will contain relevant information about the loop's completion.

fromInclusivetoExclusive보다 크거나 같으면 메서드가 반복을 수행 하지 않고 즉시 반환 됩니다.If fromInclusive is greater than or equal to toExclusive, then the method returns immediately without performing any iterations.

추가 정보

For(Int64, Int64, Action<Int64>)

64비트 인덱스를 사용하여 반복을 병렬로 실행할 수 있는 for 루프를 실행합니다.Executes a for loop with 64-bit indexes in which iterations may run in parallel.

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

시작 인덱스(포함)입니다.The start index, inclusive.

toExclusive
Int64

끝 인덱스(제외)입니다.The end index, exclusive.

body
Action<Int64>

반복당 한 번씩 호출되는 대리자입니다.The delegate that is invoked once per iteration.

반환

완료된 루프 부분에 대한 정보가 포함된 구조체입니다.A structure that contains information about which portion of the loop completed.

예외

body 인수가 null인 경우The body argument is null.

모든 스레드에서 throw 된 모든 개별 예외를 포함 하는 예외입니다.The exception that contains all the individual exceptions thrown on all threads.

설명

body 대리자는 반복 범위 (fromInclusive, toExclusive)의 각 값에 대해 한 번씩 호출 됩니다.The body delegate is invoked once for each value in the iteration range (fromInclusive, toExclusive). 반복 횟수 (Int64)가 매개 변수로 제공 됩니다.It is provided with the iteration count (Int64) as a parameter.

fromInclusivetoExclusive크거나 같으면 메서드가 반복을 수행 하지 않고 즉시 반환 됩니다.If fromInclusive is greater than or equal to toExclusive, the method returns immediately without performing any iterations.

추가 정보

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

반복을 병렬로 실행할 수 있고 루프 옵션을 구성할 수 있으며 루프 상태를 모니터링 및 조작할 수 있는 for 작업을 루프를 실행합니다.Executes a for loop in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated.

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

매개 변수

fromInclusive
Int32

시작 인덱스(포함)입니다.The start index, inclusive.

toExclusive
Int32

끝 인덱스(제외)입니다.The end index, exclusive.

parallelOptions
ParallelOptions

이 작업의 동작을 구성하는 개체입니다.An object that configures the behavior of this operation.

body
Action<Int32,ParallelLoopState>

반복당 한 번씩 호출되는 대리자입니다.The delegate that is invoked once per iteration.

반환

완료된 루프 부분에 대한 정보가 포함된 구조체입니다.A structure that contains information about which portion of the loop completed.

예외

CancellationToken 인수의 parallelOptions이 취소된 경우The CancellationToken in the parallelOptions argument is canceled.

body 인수가 null인 경우The body argument is null.

-또는--or- parallelOptions 인수가 null인 경우The parallelOptions argument is null.

모든 스레드에서 throw 된 모든 개별 예외를 포함 하는 예외입니다.The exception that contains all the individual exceptions thrown on all threads.

CancellationTokenSourceCancellationToken과 연결된 parallelOptions가 삭제되었습니다.The CancellationTokenSource associated with the CancellationToken in the parallelOptions has been disposed.

설명

body 대리자는 반복 범위 (fromInclusive, toExclusive)의 각 값에 대해 한 번씩 호출 됩니다.The body delegate is invoked once for each value in the iteration range (fromInclusive, toExclusive). 이 매개 변수는 반복 횟수 (Int32) 및 루프를 중간에 중단 하는 데 사용할 수 있는 ParallelLoopState 인스턴스와 같은 매개 변수를 제공 합니다.It is provided with the following parameters: the iteration count (Int32), and a ParallelLoopState instance that may be used to break out of the loop prematurely.

fromInclusivetoExclusive크거나 같으면 메서드가 반복을 수행 하지 않고 즉시 반환 됩니다.If fromInclusive is greater than or equal to toExclusive, the method returns immediately without performing any iterations.

추가 정보

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

반복을 병렬로 실행할 수 있고 루프 옵션을 구성할 수 있는 for 루프를 실행합니다.Executes a for loop in which iterations may run in parallel and loop options can be configured.

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

매개 변수

fromInclusive
Int32

시작 인덱스(포함)입니다.The start index, inclusive.

toExclusive
Int32

끝 인덱스(제외)입니다.The end index, exclusive.

parallelOptions
ParallelOptions

이 작업의 동작을 구성하는 개체입니다.An object that configures the behavior of this operation.

body
Action<Int32>

반복당 한 번씩 호출되는 대리자입니다.The delegate that is invoked once per iteration.

반환

완료된 루프의 부분에 대한 정보가 포함된 구조체입니다.A structure that contains information about which portion of the loop completed.

예외

CancellationToken 인수의 parallelOptions이 취소된 경우The CancellationToken in the parallelOptions argument is canceled.

body 인수가 null인 경우The body argument is null.

-또는--or- parallelOptions 인수가 null인 경우The parallelOptions argument is null.

모든 스레드에서 throw 된 모든 개별 예외를 포함 하는 예외입니다.The exception that contains all the individual exceptions thrown on all threads.

CancellationTokenSourceCancellationToken과 연결된 parallelOptions가 삭제되었습니다.The CancellationTokenSource associated with the CancellationToken in the parallelOptions has been disposed.

예제

다음 예제에서는 병렬 루프를 취소 하는 방법을 보여 줍니다.The following example shows how to cancel a parallel loop:


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)의 각 값에 대해 한 번씩 호출 됩니다.The body delegate is invoked once for each value in the iteration range (fromInclusive, toExclusive). 반복 횟수 (Int32)가 매개 변수로 제공 됩니다.It is provided with the iteration count (Int32) as a parameter.

fromInclusivetoExclusive보다 크거나 같으면 메서드가 반복을 수행 하지 않고 즉시 반환 됩니다.If fromInclusive is greater than or equal to toExclusive, then the method returns immediately without performing any iterations.

추가 정보

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

64비트 인덱스를 사용하여 반복을 병렬로 실행할 수 있고 루프 옵션을 구성할 수 있으며 루프 상태를 모니터링 및 조작할 수 있는 for 루프를 실행합니다.Executes a for loop with 64-bit indexes in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated.

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

매개 변수

fromInclusive
Int64

시작 인덱스(포함)입니다.The start index, inclusive.

toExclusive
Int64

끝 인덱스(제외)입니다.The end index, exclusive.

parallelOptions
ParallelOptions

이 작업의 동작을 구성하는 개체입니다.An object that configures the behavior of this operation.

body
Action<Int64,ParallelLoopState>

반복당 한 번씩 호출되는 대리자입니다.The delegate that is invoked once per iteration.

반환

완료된 루프 부분에 대한 정보가 포함된 구조체입니다.A structure that contains information about which portion of the loop completed.

예외

CancellationToken 인수의 parallelOptions이 취소된 경우The CancellationToken in the parallelOptions argument is canceled.

body 인수가 null인 경우The body argument is null.

-또는--or- parallelOptions 인수가 null인 경우The parallelOptions argument is null.

모든 스레드에서 throw 된 모든 개별 예외를 포함 하는 예외입니다.The exception that contains all the individual exceptions thrown on all threads.

CancellationTokenSourceCancellationToken과 연결된 parallelOptions가 삭제되었습니다.The CancellationTokenSource associated with the CancellationToken in the parallelOptions has been disposed.

예제

다음 예제에서는 ParallelOptions 개체에 Parallel.For 메서드를 사용 하는 방법을 보여 줍니다.The following example shows how to use the Parallel.For method with a ParallelOptions object:

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)의 각 값에 대해 한 번씩 호출 됩니다.The body delegate is invoked once for each value in the iteration range (fromInclusive, toExclusive). 이 매개 변수는 반복 횟수 (Int64) 및 루프를 중간에 중단 하는 데 사용할 수 있는 ParallelLoopState 인스턴스와 같은 매개 변수를 제공 합니다.It is provided with the following parameters: the iteration count (Int64), and a ParallelLoopState instance that may be used to break out of the loop prematurely.

fromInclusivetoExclusive크거나 같으면 메서드가 반복을 수행 하지 않고 즉시 반환 됩니다.If fromInclusive is greater than or equal to toExclusive, the method returns immediately without performing any iterations.

추가 정보

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

64비트 인덱스를 사용하여 반복을 병렬로 실행할 수 있고 루프 옵션을 구성할 수 있는 for 루프를 실행합니다.Executes a for loop with 64-bit indexes in which iterations may run in parallel and loop options can be configured.

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

매개 변수

fromInclusive
Int64

시작 인덱스(포함)입니다.The start index, inclusive.

toExclusive
Int64

끝 인덱스(제외)입니다.The end index, exclusive.

parallelOptions
ParallelOptions

이 작업의 동작을 구성하는 개체입니다.An object that configures the behavior of this operation.

body
Action<Int64>

반복당 한 번씩 호출되는 대리자입니다.The delegate that is invoked once per iteration.

반환

완료된 루프 부분에 대한 정보가 포함된 구조체입니다.A structure that contains information about which portion of the loop completed.

예외

CancellationToken 인수의 parallelOptions이 취소된 경우The CancellationToken in the parallelOptions argument is canceled.

body 인수가 null인 경우The body argument is null.

-또는--or- parallelOptions 인수가 null인 경우The parallelOptions argument is null.

모든 스레드에서 throw 된 모든 개별 예외를 포함 하는 예외입니다.The exception that contains all the individual exceptions thrown on all threads.

CancellationTokenSourceCancellationToken과 연결된 parallelOptions가 삭제되었습니다.The CancellationTokenSource associated with the CancellationToken in the parallelOptions has been disposed.

예제

다음 예제에서는 ParallelOptions를 사용 하 여 사용자 지정 작업 스케줄러를 지정 하는 방법을 보여 줍니다.The following example shows how to use ParallelOptions to specify a custom task scheduler:

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 비트 인덱스를 지원합니다.Supports 64-bit indexes. body 대리자는 반복 범위 (fromInclusive, toExclusive)의 각 값에 대해 한 번씩 호출 됩니다.The body delegate is invoked once for each value in the iteration range (fromInclusive, toExclusive). 반복 횟수 (Int64)가 매개 변수로 제공 됩니다.It is provided with the iteration count (Int64) as a parameter.

fromInclusivetoExclusive보다 크거나 같으면 메서드가 반복을 수행 하지 않고 즉시 반환 됩니다.If fromInclusive is greater than or equal to toExclusive, then the method returns immediately without performing any iterations.

추가 정보

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

64비트 인덱스와 스레드 로컬 데이터를 사용하여 반복을 병렬로 실행할 수 있고 루프 옵션을 구성할 수 있으며 루프 상태를 모니터링 및 조작할 수 있는 for 루프를 실행합니다.Executes a for loop with 64-bit indexes and thread-local data 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 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

형식 매개 변수

TLocal

스레드 로컬 데이터의 형식입니다.The type of the thread-local data.

매개 변수

fromInclusive
Int64

시작 인덱스(포함)입니다.The start index, inclusive.

toExclusive
Int64

끝 인덱스(제외)입니다.The end index, exclusive.

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 thread.

body
Func<Int64,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 thread.

반환

완료된 루프 부분에 대한 정보가 포함된 구조체입니다.A structure that contains information about which portion of the loop completed.

예외

body 인수가 null인 경우The body argument is null.

-또는--or- localInit 인수가 null인 경우The localInit argument is null.

-또는--or- localFinally 인수가 null인 경우The localFinally argument is null.

-또는--or- parallelOptions 인수가 null인 경우The parallelOptions argument is null.

CancellationToken 인수의 parallelOptions이 취소된 경우The CancellationToken in the parallelOptions argument is canceled.

CancellationTokenSourceCancellationToken과 연결된 parallelOptions가 삭제되었습니다.The CancellationTokenSource associated with the CancellationToken in the parallelOptions has been disposed.

모든 스레드에서 throw 된 모든 개별 예외를 포함 하는 예외입니다.The exception that contains all the individual exceptions thrown on all threads.

설명

body 대리자는 반복 범위 (fromInclusive, toExclusive)의 각 값에 대해 한 번씩 호출 됩니다.The body delegate is invoked once for each value in the iteration range (fromInclusive, toExclusive). 반복 횟수 (Int64), 루프를 중단 하는 데 사용할 수 있는 ParallelLoopState 인스턴스, 같은 스레드에서 실행 되는 반복 간에 공유 될 수 있는 일부 로컬 상태와 같은 매개 변수가 제공 됩니다.It is provided with the following parameters: the iteration count (Int64), 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.

localInit 대리자는 루프의 실행에 참여 하는 각 스레드에 대해 한 번 호출 되며 각 스레드에 대 한 초기 로컬 상태를 반환 합니다.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 threads. 이러한 초기 상태는 각 스레드에서 첫 번째 body 호출에 전달 됩니다.These initial states are passed to the first body invocations on each thread. 그런 다음 모든 후속 본문 호출은 다음 본문 호출에 전달 되는 가능한 경우 수정 된 상태 값을 반환 합니다.Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. 마지막으로 각 스레드의 마지막 본문 호출이 localFinally 대리자에 전달 되는 상태 값을 반환 합니다.Finally, the last body invocation on each thread returns a state value that is passed to the localFinally delegate. 각 스레드의 로컬 상태에 대해 최종 동작을 수행 하기 위해 스레드 당 한 번씩 localFinally 대리자가 호출 됩니다.The localFinally delegate is invoked once per thread to perform a final action on each thread's local state. 이 대리자; 여러 스레드에서 동시에 호출 될 수 있습니다. 따라서 모든 공유 변수에 대 한 액세스를 동기화 해야 합니다.This delegate might be invoked concurrently on multiple threads; therefore, you must synchronize access to any shared variables.

Parallel.For 메서드는 기존 작업이 완료 되 고 새 작업으로 대체 될 때 실행 수명 동안 스레드 보다 많은 작업을 사용할 수 있습니다.The Parallel.For method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. 이렇게 하면 기본 TaskScheduler 개체가 루프를 처리 하는 스레드를 추가, 변경 또는 제거할 수 있습니다.This gives the underlying TaskScheduler object the chance to add, change, or remove threads that service the loop.

fromInclusivetoExclusive보다 크거나 같으면 메서드가 반복을 수행 하지 않고 즉시 반환 됩니다.If fromInclusive is greater than or equal to toExclusive, then the method returns immediately without performing any iterations.

추가 정보

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

스레드 로컬 데이터를 사용하여 반복을 병렬로 실행할 수 있고 루프 옵션을 구성할 수 있으며 루프 상태를 모니터링 및 조작할 수 있는 for 루프를 실행합니다.Executes a for loop with thread-local data 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 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

형식 매개 변수

TLocal

스레드 로컬 데이터의 형식입니다.The type of the thread-local data.

매개 변수

fromInclusive
Int32

시작 인덱스(포함)입니다.The start index, inclusive.

toExclusive
Int32

끝 인덱스(제외)입니다.The end index, exclusive.

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<Int32,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.

반환

완료된 루프 부분에 대한 정보가 포함된 구조체입니다.A structure that contains information about which portion of the loop completed.

예외

body 인수가 null인 경우The body argument is null.

-또는--or- localInit 인수가 null인 경우The localInit argument is null.

-또는--or- localFinally 인수가 null인 경우The localFinally argument is null.

-또는--or- parallelOptions 인수가 null인 경우The parallelOptions argument is null.

CancellationToken 인수의 parallelOptions이 취소된 경우The CancellationToken in the parallelOptions argument is canceled.

CancellationTokenSourceCancellationToken과 연결된 parallelOptions가 삭제되었습니다.The CancellationTokenSource associated with the CancellationToken in the parallelOptions has been disposed.

모든 스레드에서 throw 된 모든 개별 예외를 포함 하는 예외입니다.The exception that contains all the individual exceptions thrown on all threads.

예제

다음 예제에서는 스레드 지역 변수를 사용 하 여 많은 시간이 오래 걸리는 작업의 결과의 합계를 계산 합니다.The following example uses thread-local variables to compute the sum of the results of many lengthy operations. 이 예제에서는 병렬 처리 수준이 4 개로 제한합니다.This example limits the degree of parallelism to four.

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)의 각 값에 대해 한 번씩 호출 됩니다.The body delegate is invoked once for each value in the iteration range (fromInclusive, toExclusive). 반복 횟수 (Int32), 루프를 중단 하는 데 사용할 수 있는 ParallelLoopState 인스턴스 및 동일한 작업에서 실행 되는 반복 간에 공유 될 수 있는 일부 로컬 상태 매개 변수가 제공 됩니다.It is provided with the following parameters: the iteration count (Int32), 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 task.

localInit 대리자는 루프의 실행에 참여 하는 각 작업에 대해 한 번 호출 되 고 각 작업에 대 한 초기 로컬 상태를 반환 합니다.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. 이러한 초기 상태는 각 작업에 대 한 첫 번째 body 호출에 전달 됩니다.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. 마지막으로, 각 작업의 마지막 본문 호출은 localFinally 대리자에 전달 되는 상태 값을 반환 합니다.Finally, the last body invocation on each task returns a state value that is passed to the localFinally delegate. 각 작업의 로컬 상태에 대해 최종 동작을 수행 하는 작업 당 한 번 호출 되는 localFinally 대리자입니다.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 threads; therefore, you must synchronize access to any shared variables.

Parallel.For 메서드는 기존 작업이 완료 되 고 새 작업으로 대체 될 때 실행 수명 동안 스레드 보다 많은 작업을 사용할 수 있습니다.The Parallel.For method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. 이렇게 하면 기본 TaskScheduler 개체가 루프를 처리 하는 스레드를 추가, 변경 또는 제거할 수 있습니다.This gives the underlying TaskScheduler object the chance to add, change, or remove threads that service the loop.

fromInclusivetoExclusive보다 크거나 같으면 메서드가 반복을 수행 하지 않고 즉시 반환 됩니다.If fromInclusive is greater than or equal to toExclusive, then the method returns immediately without performing any iterations.

추가 정보

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

스레드 로컬 데이터를 사용하여 반복을 병렬로 실행할 수 있고 루프 상태를 모니터링 및 조작할 수 있는 for 루프를 실행합니다.Executes a for loop with thread-local data in which iterations may run in parallel, and the state of the loop can be monitored and manipulated.

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

스레드 로컬 데이터의 형식입니다.The type of the thread-local data.

매개 변수

fromInclusive
Int32

시작 인덱스(포함)입니다.The start index, inclusive.

toExclusive
Int32

끝 인덱스(제외)입니다.The end index, exclusive.

localInit
Func<TLocal>

각 작업에 대한 로컬 데이터의 초기 상태를 반환하는 함수 대리자입니다.The function delegate that returns the initial state of the local data for each task.

body
Func<Int32,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.

반환

완료된 루프의 부분에 대한 정보가 포함된 구조체입니다.A structure that contains information about which portion of the loop completed.

예외

body 인수가 null인 경우The body argument is null.

-또는--or- localInit 인수가 null인 경우The localInit argument is null.

-또는--or- localFinally 인수가 null인 경우The localFinally argument is null.

모든 스레드에서 throw 된 모든 개별 예외를 포함 하는 예외입니다.The exception that contains all the individual exceptions thrown on all threads.

설명

body 대리자는 반복 범위 (fromInclusive, toExclusive)의 각 값에 대해 한 번씩 호출 됩니다.The body delegate is invoked once for each value in the iteration range (fromInclusive, toExclusive). 반복 횟수 (Int32), 루프를 중단 하는 데 사용할 수 있는 ParallelLoopState 인스턴스, 같은 스레드에서 실행 되는 반복 간에 공유 될 수 있는 일부 로컬 상태와 같은 매개 변수가 제공 됩니다.It is provided with the following parameters: the iteration count (Int32), 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.

localInit 대리자는 루프의 실행에 참여 하는 각 작업에 대해 한 번 호출 되 고 각 작업에 대 한 초기 로컬 상태를 반환 합니다.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. 이러한 초기 상태는 각 작업에 대 한 첫 번째 body 호출에 전달 됩니다.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. 마지막으로, 각 작업의 마지막 본문 호출은 localFinally 대리자에 전달 되는 상태 값을 반환 합니다.Finally, the last body invocation on each task returns a state value that is passed to the localFinally delegate. 각 작업의 로컬 상태에 대해 최종 동작을 수행 하는 작업 당 한 번 호출 되는 localFinally 대리자입니다.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.

Parallel.For 메서드는 기존 작업이 완료 되 고 새 작업으로 대체 될 때 실행 수명 동안 스레드 보다 많은 작업을 사용할 수 있습니다.The Parallel.For method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. 이렇게 하면 기본 TaskScheduler 개체가 루프를 처리 하는 스레드를 추가, 변경 또는 제거할 수 있습니다.This gives the underlying TaskScheduler object the chance to add, change, or remove threads that service the loop.

fromInclusivetoExclusive보다 크거나 같으면 메서드가 반복을 수행 하지 않고 즉시 반환 됩니다.If fromInclusive is greater than or equal to toExclusive, then the method returns immediately without performing any iterations.

이 메서드를 사용 하는 예제는 방법: 병렬 쓰기를 참조 하세요. 스레드 지역 변수가 있는 For 루프For an example that uses this method, see How to: Write a Parallel.For Loop with Thread-Local Variables.

추가 정보

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

64비트 인덱스와 스레드 로컬 데이터를 사용하여 반복을 병렬로 실행할 수 있고 루프 상태를 모니터링 및 조작할 수 있는 for 루프를 실행합니다.Executes a for loop with 64-bit indexes and thread-local data in which iterations may run in parallel, and the state of the loop can be monitored and manipulated.

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

스레드 로컬 데이터의 형식입니다.The type of the thread-local data.

매개 변수

fromInclusive
Int64

시작 인덱스(포함)입니다.The start index, inclusive.

toExclusive
Int64

끝 인덱스(제외)입니다.The end index, exclusive.

localInit
Func<TLocal>

각 작업에 대한 로컬 데이터의 초기 상태를 반환하는 함수 대리자입니다.The function delegate that returns the initial state of the local data for each task.

body
Func<Int64,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.

반환

완료된 루프 부분에 대한 정보가 포함된 구조체입니다.A structure that contains information about which portion of the loop completed.

예외

body 인수가 null인 경우The body argument is null.

-또는--or- localInit 인수가 null인 경우The localInit argument is null.

-또는--or- localFinally 인수가 null인 경우The localFinally argument is null.

모든 스레드에서 throw 된 모든 개별 예외를 포함 하는 예외입니다.The exception that contains all the individual exceptions thrown on all threads.

설명

body 대리자는 반복 범위 (fromInclusive, toExclusive)의 각 값에 대해 한 번씩 호출 됩니다.The body delegate is invoked once for each value in the iteration range (fromInclusive, toExclusive). 반복 횟수 (Int64), 루프를 중단 하는 데 사용할 수 있는 ParallelLoopState 인스턴스 및 동일한 작업에서 실행 되는 반복 간에 공유 될 수 있는 일부 로컬 상태 매개 변수가 제공 됩니다.It is provided with the following parameters: the iteration count (Int64), 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 task.

localInit 대리자는 루프의 실행에 참여 하는 각 작업에 대해 한 번 호출 되 고 각 작업에 대 한 초기 로컬 상태를 반환 합니다.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. 이러한 초기 상태는 각 작업에 대 한 첫 번째 body 호출에 전달 됩니다.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. 마지막으로, 각 작업의 마지막 본문 호출은 localFinally 대리자에 전달 되는 상태 값을 반환 합니다.Finally, the last body invocation on each task returns a state value that is passed to the localFinally delegate. 각 작업의 로컬 상태에 대해 최종 동작을 수행 하는 작업 당 한 번 호출 되는 localFinally 대리자입니다.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.

Parallel.For 메서드는 기존 작업이 완료 되 고 새 작업으로 대체 될 때 실행 수명 동안 스레드 보다 많은 작업을 사용할 수 있습니다.The Parallel.For method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. 이렇게 하면 기본 TaskScheduler 개체가 루프를 처리 하는 스레드를 추가, 변경 또는 제거할 수 있습니다.This gives the underlying TaskScheduler object the chance to add, change, or remove threads that service the loop.

fromInclusivetoExclusive보다 크거나 같으면 메서드가 반복을 수행 하지 않고 즉시 반환 됩니다.If fromInclusive is greater than or equal to toExclusive, then the method returns immediately without performing any iterations.

이 메서드를 사용 하는 예제는 방법: 병렬 쓰기를 참조 하세요. 스레드 지역 변수가 있는 For 루프For an example that uses this method, see How to: Write a Parallel.For Loop with Thread-Local Variables.

추가 정보

적용 대상