CancellationTokenSource CancellationTokenSource CancellationTokenSource CancellationTokenSource Class

정의

취소되도록 CancellationToken에 신호를 보냅니다.Signals to a CancellationToken that it should be canceled.

public ref class CancellationTokenSource : IDisposable
[System.Runtime.InteropServices.ComVisible(false)]
public class CancellationTokenSource : IDisposable
type CancellationTokenSource = class
    interface IDisposable
Public Class CancellationTokenSource
Implements IDisposable
상속
CancellationTokenSourceCancellationTokenSourceCancellationTokenSourceCancellationTokenSource
특성
구현

예제

다음 예제에서는 정수 값 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.

설명

부터 .NET Framework 4.NET Framework 4,.NET Framework 통합된 모델을 사용 하 여 두 개체를 포함 하는 비동기 또는 장기 실행 동기 작업의 협조적 취소:Starting with the .NET Framework 4.NET Framework 4, the .NET Framework uses a unified model for cooperative cancellation of asynchronous or long-running synchronous operations that involves two objects:

협조적 취소 모델을 구현하는 일반적인 패턴은 다음과 같습니다.The general pattern for implementing the cooperative cancellation model is:

자세한 내용은 관리되는 스레드의 취소를 참조하세요.For more information, see Cancellation in Managed Threads.

중요

이 형식이 구현 하는 IDisposable 인터페이스입니다.This type implements the IDisposable interface. 형식의 인스턴스를 사용 하 여 마쳤으면 직접 또는 간접적으로으로 삭제 해야 있습니다.When you have finished using an instance of the type, you should dispose of it either directly or indirectly. 직접 형식의 dispose 호출 해당 Dispose 의 메서드를 try / catch 블록입니다.To dispose of the type directly, call its Dispose method in a try/catch block. 삭제 하지 직접, 언어 구문 같은 사용 using (C#에서) 또는 Using (Visual Basic에서는).To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). 자세한 내용은 "를 사용 하는 개체는 구현 IDisposable" 섹션을 참조 하세요.를 IDisposable 인터페이스 항목입니다.For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

생성자

CancellationTokenSource() CancellationTokenSource() CancellationTokenSource() CancellationTokenSource()

CancellationTokenSource 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the CancellationTokenSource class.

CancellationTokenSource(Int32) CancellationTokenSource(Int32) CancellationTokenSource(Int32) CancellationTokenSource(Int32)

지정된 지연(밀리초) 후에 취소될 CancellationTokenSource의 새 인스턴스를 초기화합니다.Initializes a new instance of the CancellationTokenSource class that will be canceled after the specified delay in milliseconds.

CancellationTokenSource(TimeSpan) CancellationTokenSource(TimeSpan) CancellationTokenSource(TimeSpan) CancellationTokenSource(TimeSpan)

지정된 시간 범위 후에 취소될 CancellationTokenSource의 새 인스턴스를 초기화합니다.Initializes a new instance of the CancellationTokenSource class that will be canceled after the specified time span.

속성

IsCancellationRequested IsCancellationRequested IsCancellationRequested IsCancellationRequested

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

Token Token Token Token

CancellationToken와 연결된 CancellationTokenSource를 가져옵니다.Gets the CancellationToken associated with this CancellationTokenSource.

메서드

Cancel() Cancel() Cancel() Cancel()

취소 요청을 전달합니다.Communicates a request for cancellation.

Cancel(Boolean) Cancel(Boolean) Cancel(Boolean) Cancel(Boolean)

예외가 발생한 경우 취소 요청을 전달하고 나머지 콜백과 취소 가능한 작업을 처리해야 하는지를 지정합니다.Communicates a request for cancellation, and specifies whether remaining callbacks and cancelable operations should be processed if an exception occurs.

CancelAfter(Int32) CancelAfter(Int32) CancelAfter(Int32) CancelAfter(Int32)

지정된 수(밀리초) 후에 이 CancellationTokenSource에 취소 작업을 예약합니다.Schedules a cancel operation on this CancellationTokenSource after the specified number of milliseconds.

CancelAfter(TimeSpan) CancelAfter(TimeSpan) CancelAfter(TimeSpan) CancelAfter(TimeSpan)

지정된 시간 범위 후에 이 CancellationTokenSource에 취소 작업을 예약합니다.Schedules a cancel operation on this CancellationTokenSource after the specified time span.

CreateLinkedTokenSource(CancellationToken, CancellationToken) CreateLinkedTokenSource(CancellationToken, CancellationToken) CreateLinkedTokenSource(CancellationToken, CancellationToken) CreateLinkedTokenSource(CancellationToken, CancellationToken)

취소된 상태인 원본 토큰이 있는 경우 취소된 상태가 되는 CancellationTokenSource를 만듭니다.Creates a CancellationTokenSource that will be in the canceled state when any of the source tokens are in the canceled state.

CreateLinkedTokenSource(CancellationToken[]) CreateLinkedTokenSource(CancellationToken[]) CreateLinkedTokenSource(CancellationToken[]) CreateLinkedTokenSource(CancellationToken[])

지정된 배열에 소스 토큰이 하나라도 취소된 상태가 되는 경우 취소된 상태가 되는 CancellationTokenSource를 만듭니다.Creates a CancellationTokenSource that will be in the canceled state when any of the source tokens in the specified array are in the canceled state.

Dispose() Dispose() Dispose() Dispose()

CancellationTokenSource 클래스의 현재 인스턴스에서 사용하는 모든 리소스를 해제합니다.Releases all resources used by the current instance of the CancellationTokenSource class.

Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

CancellationTokenSource 클래스에 사용되는 관리되지 않는 리소스를 해제하고, 필요에 따라 관리되는 리소스를 해제합니다.Releases the unmanaged resources used by the CancellationTokenSource class and optionally releases the managed resources.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

지정한 개체와 현재 개체가 같은지 여부를 확인합니다.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

기본 해시 함수로 작동합니다.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

현재 인스턴스의 Type을 가져옵니다.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

현재 개체를 나타내는 문자열을 반환합니다.Returns a string that represents the current object.

(Inherited from Object)

적용 대상

스레드 보안

모든 public 및 protected 멤버만 CancellationTokenSource 는 스레드로부터 안전 하 고 제외 여러 스레드에서 동시에 사용할 수 있습니다 Dispose()는 때만 사용 해야 다른 모든 작업에는 CancellationTokenSource 개체 완료.All public and protected members of CancellationTokenSource are thread-safe and may be used concurrently from multiple threads, with the exception of Dispose(), which must only be used when all other operations on the CancellationTokenSource object have completed.

추가 정보