CancellationToken 구조체

정의

작업을 취소하지 않아야 함을 전파합니다.Propagates notification that operations should be canceled.

public value class 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.

이 예제에서는 작업의 가능한 취소를 처리 하려면 인스턴스화합니다를 CancellationTokenSource 에 전달 되는 취소 토큰을 생성 하는 개체를 TaskFactory 개체입니다.To handle the possible cancellation of the operation, the example instantiates a CancellationTokenSource object that generates a cancellation token which is passed to a TaskFactory object. TaskFactory 개체 취소 토큰에 전달 작업을 각각 특정 계측에 대 한 정보를 수집 하는 일을 담당 합니다.The TaskFactory object in turn 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 because it has been cancelled, the call to 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.

설명

A CancellationToken 스레드를 스레드 풀 작업 항목 간 협조적 취소를 사용 하도록 설정 하거나 Task 개체입니다.A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. 취소 토큰을 인스턴스화하여 만들를 CancellationTokenSource 에서 취소 토큰을 관리 하는 개체를 검색할 해당 CancellationTokenSource.Token 속성.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.CancelIsCancellationRequested 취소 토큰의 모든 복사본에 대 한 속성이 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.

적용 대상

스레드 보안

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

추가 정보