CancellationToken 구조체

정의

작업을 취소해야 한다는 알림을 전파합니다.Propagates notification that operations should be canceled.

public value class CancellationToken
public struct CancellationToken
[System.Runtime.InteropServices.ComVisible(false)]
public struct CancellationToken
type CancellationToken = struct
Public Structure CancellationToken
상속
CancellationToken
특성

예제

다음 예제에서는 정수 값 10 11 개의 다양 한 계측에서 읽는 데이터 컬렉션 애플리케이션을 에뮬레이트 하려면 난수 생성기를 사용 합니다.The following example uses a random number generator to emulate a data collection application that reads 10 integral values from eleven different instruments. 0 값 작업을 취소 해야 하는 경우와 없는 전체 평균을 계산 해야 하는 하나의 계측에 대 한 측정에 실패 했음을 나타냅니다.A value of zero indicates that the measurement has failed for one instrument, in which case the operation should be cancelled and no overall mean should be computed.

이 예제에서는 작업의 가능한 취소를 처리 하기 위해 TaskFactory 개체에 전달 되는 취소 토큰을 생성 하는 CancellationTokenSource 개체를 인스턴스화합니다.To handle the possible cancellation of the operation, the example instantiates a CancellationTokenSource object that generates a cancellation token that's passed to a TaskFactory object. 차례로 TaskFactory 개체는 특정 계기에 대 한 판독값을 담당 하는 각 작업에 취소 토큰을 전달 합니다.In turn, the TaskFactory object passes the cancellation token to each of the tasks responsible for collecting readings for a particular instrument. 모든 판독값이 성공적으로 수집 된 후에만 평균이 계산 되도록 TaskFactory.ContinueWhenAll<TAntecedentResult,TResult>(Task<TAntecedentResult>[], Func<Task<TAntecedentResult>[],TResult>, CancellationToken) 메서드가 호출 됩니다.The TaskFactory.ContinueWhenAll<TAntecedentResult,TResult>(Task<TAntecedentResult>[], Func<Task<TAntecedentResult>[],TResult>, CancellationToken) method is called to ensure that the mean is computed only after all readings have been gathered successfully. 작업이 취소 되어 완료 되지 않은 경우 TaskFactory.ContinueWhenAll 메서드에서 예외를 throw 합니다.If a task has not completed because it was cancelled, the TaskFactory.ContinueWhenAll method throws an exception.

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

public class Example
{
   public static void Main()
   {
      // Define the cancellation token.
      CancellationTokenSource source = new CancellationTokenSource();
      CancellationToken token = source.Token;

      Random rnd = new Random();
      Object lockObj = new Object();
      
      List<Task<int[]>> tasks = new List<Task<int[]>>();
      TaskFactory factory = new TaskFactory(token);
      for (int taskCtr = 0; taskCtr <= 10; taskCtr++) {
         int iteration = taskCtr + 1;
         tasks.Add(factory.StartNew( () => {
                                       int value;
                                       int[] values = new int[10];
                                       for (int ctr = 1; ctr <= 10; ctr++) {
                                          lock (lockObj) {
                                             value = rnd.Next(0,101);
                                          }
                                          if (value == 0) { 
                                             source.Cancel();
                                             Console.WriteLine("Cancelling at task {0}", iteration);
                                             break;
                                          }   
                                          values[ctr-1] = value; 
                                       }
                                       return values;
                                    }, token));   
      }
      try {
         Task<double> fTask = factory.ContinueWhenAll(tasks.ToArray(), 
                                                      (results) => {
                                                         Console.WriteLine("Calculating overall mean...");
                                                         long sum = 0;
                                                         int n = 0; 
                                                         foreach (var t in results) {
                                                            foreach (var r in t.Result) {
                                                                  sum += r;
                                                                  n++;
                                                               }
                                                         }
                                                         return sum/(double) n;
                                                      } , token);
         Console.WriteLine("The mean is {0}.", fTask.Result);
      }   
      catch (AggregateException ae) {
         foreach (Exception e in ae.InnerExceptions) {
            if (e is TaskCanceledException)
               Console.WriteLine("Unable to compute mean: {0}", 
                                 ((TaskCanceledException) e).Message);
            else
               Console.WriteLine("Exception: " + e.GetType().Name);
         }
      }
      finally {
         source.Dispose();
      }
   }
}
// Repeated execution of the example produces output like the following:
//       Cancelling at task 5
//       Unable to compute mean: A task was canceled.
//       
//       Cancelling at task 10
//       Unable to compute mean: A task was canceled.
//       
//       Calculating overall mean...
//       The mean is 5.29545454545455.
//       
//       Cancelling at task 4
//       Unable to compute mean: A task was canceled.
//       
//       Cancelling at task 5
//       Unable to compute mean: A task was canceled.
//       
//       Cancelling at task 6
//       Unable to compute mean: A task was canceled.
//       
//       Calculating overall mean...
//       The mean is 4.97363636363636.
//       
//       Cancelling at task 4
//       Unable to compute mean: A task was canceled.
//       
//       Cancelling at task 5
//       Unable to compute mean: A task was canceled.
//       
//       Cancelling at task 4
//       Unable to compute mean: A task was canceled.
//       
//       Calculating overall mean...
//       The mean is 4.86545454545455.
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      ' Define the cancellation token.
      Dim source As New CancellationTokenSource()
      Dim token As CancellationToken = source.Token

      Dim lockObj As New Object()
      Dim rnd As New Random

      Dim tasks As New List(Of Task(Of Integer()))
      Dim factory As New TaskFactory(token)
      For taskCtr As Integer = 0 To 10
         Dim iteration As Integer = taskCtr + 1
         tasks.Add(factory.StartNew(Function()
                                       Dim value, values(9) As Integer
                                       For ctr As Integer = 1 To 10
                                          SyncLock lockObj
                                             value = rnd.Next(0,101)
                                          End SyncLock
                                          If value = 0 Then 
                                             source.Cancel
                                             Console.WriteLine("Cancelling at task {0}", iteration)
                                             Exit For
                                          End If   
                                          values(ctr-1) = value 
                                       Next
                                       Return values
                                    End Function, token))   
         
      Next
      Try
         Dim fTask As Task(Of Double) = factory.ContinueWhenAll(tasks.ToArray(), 
                                                         Function(results)
                                                            Console.WriteLine("Calculating overall mean...")
                                                            Dim sum As Long
                                                            Dim n As Integer 
                                                            For Each t In results
                                                               For Each r In t.Result
                                                                  sum += r
                                                                  n+= 1
                                                               Next
                                                            Next
                                                            Return sum/n
                                                         End Function, token)
         Console.WriteLine("The mean is {0}.", fTask.Result)
      Catch ae As AggregateException
         For Each e In ae.InnerExceptions
            If TypeOf e Is TaskCanceledException
               Console.WriteLine("Unable to compute mean: {0}", 
                                 CType(e, TaskCanceledException).Message)
            Else
               Console.WriteLine("Exception: " + e.GetType().Name)
            End If   
         Next
      Finally
         source.Dispose()
      End Try                                                          
   End Sub
End Module
' Repeated execution of the example produces output like the following:
'       Cancelling at task 5
'       Unable to compute mean: A task was canceled.
'       
'       Cancelling at task 10
'       Unable to compute mean: A task was canceled.
'       
'       Calculating overall mean...
'       The mean is 5.29545454545455.
'       
'       Cancelling at task 4
'       Unable to compute mean: A task was canceled.
'       
'       Cancelling at task 5
'       Unable to compute mean: A task was canceled.
'       
'       Cancelling at task 6
'       Unable to compute mean: A task was canceled.
'       
'       Calculating overall mean...
'       The mean is 4.97363636363636.
'       
'       Cancelling at task 4
'       Unable to compute mean: A task was canceled.
'       
'       Cancelling at task 5
'       Unable to compute mean: A task was canceled.
'       
'       Cancelling at task 4
'       Unable to compute mean: A task was canceled.
'       
'       Calculating overall mean...
'       The mean is 4.86545454545455.

설명

CancellationToken는 스레드, 스레드 풀 작업 항목 또는 Task 개체 간의 협조적 취소를 가능 하 게 합니다.A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. CancellationTokenSource.Token 속성에서 검색 된 취소 토큰을 관리 하는 CancellationTokenSource 개체를 인스턴스화하여 취소 토큰을 만듭니다.You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource.Token property. 그런 다음 임의 개수의 스레드, 작업 또는 취소의 통지를 수신 해야 하는 작업에 취소 토큰을 전달 합니다.You then pass the cancellation token to any number of threads, tasks, or operations that should receive notice of cancellation. 취소를 시작 하는 토큰을 사용할 수 없습니다.The token cannot be used to initiate cancellation. 소유 하는 개체가 CancellationTokenSource.Cancel를 호출 하면 취소 토큰의 모든 복사본에 대 한 IsCancellationRequested 속성이 true로 설정 됩니다.When the owning object calls CancellationTokenSource.Cancel, the IsCancellationRequested property on every copy of the cancellation token is set to true. 알림을 수신 하는 개체는 적절 한 방식으로 응답할 수 있습니다.The objects that receive the notification can respond in whatever manner is appropriate.

자세한 내용 및 코드 예제 는 관리 되는 스레드의 취소를 참조 하세요.For more information and code examples see Cancellation in Managed Threads.

생성자

CancellationToken(Boolean)

CancellationToken을 초기화합니다.Initializes the CancellationToken.

속성

CanBeCanceled

이 토큰이 취소된 상태로 있을 수 있는지 여부를 가져옵니다.Gets whether this token is capable of being in the canceled state.

IsCancellationRequested

이 토큰의 취소가 요청되었는지 여부를 가져옵니다.Gets whether cancellation has been requested for this token.

None

CancellationToken 값을 반환합니다.Returns an empty CancellationToken value.

WaitHandle

토큰이 취소될 때 신호를 받는 WaitHandle을 가져옵니다.Gets a WaitHandle that is signaled when the token is canceled.

메서드

Equals(CancellationToken)

현재 CancellationToken 인스턴스와 지정한 토큰이 같은지 여부를 확인합니다.Determines whether the current CancellationToken instance is equal to the specified token.

Equals(Object)

현재 CancellationToken 인스턴스와 지정한 Object가 같은지 여부를 확인합니다.Determines whether the current CancellationToken instance is equal to the specified Object.

GetHashCode()

CancellationToken의 해시 함수 역할을 수행합니다.Serves as a hash function for a CancellationToken.

Register(Action)

CancellationToken이 취소될 때 호출할 대리자를 등록합니다.Registers a delegate that will be called when this CancellationToken is canceled.

Register(Action, Boolean)

CancellationToken이 취소될 때 호출할 대리자를 등록합니다.Registers a delegate that will be called when this CancellationToken is canceled.

Register(Action<Object>, Object)

CancellationToken이 취소될 때 호출할 대리자를 등록합니다.Registers a delegate that will be called when this CancellationToken is canceled.

Register(Action<Object>, Object, Boolean)

CancellationToken이 취소될 때 호출할 대리자를 등록합니다.Registers a delegate that will be called when this CancellationToken is canceled.

ThrowIfCancellationRequested()

이 토큰의 취소가 요청된 경우 OperationCanceledException이 발생합니다.Throws a OperationCanceledException if this token has had cancellation requested.

UnsafeRegister(Action<Object>, Object)

CancellationToken이 취소될 때 호출되는 대리자를 등록합니다.Registers a delegate that is called when this CancellationToken is canceled.

연산자

Equality(CancellationToken, CancellationToken)

CancellationToken 인스턴스가 동일한지 여부를 확인합니다.Determines whether two CancellationToken instances are equal.

Inequality(CancellationToken, CancellationToken)

CancellationToken 인스턴스가 서로 다른지 여부를 확인합니다.Determines whether two CancellationToken instances are not equal.

적용 대상

스레드 보안

CancellationToken의 모든 공용 및 보호 된 멤버는 스레드로부터 안전 하며 여러 스레드에서 동시에 사용할 수 있습니다.All public and protected members of CancellationToken are thread-safe and may be used concurrently from multiple threads.

추가 정보