이 문서는 기계 번역을 이용하여 번역되었습니다. 문서를 영문으로 보려면 영문 확인란을 선택하세요. 마우스 포인터를 텍스트 위로 이동시켜 팝업 창에서 영문 텍스트를 표시할 수도 있습니다.
번역
영문

CancellationTokenSource 클래스

 

게시 날짜: 2016년 11월

취소되도록 CancellationToken에 신호를 보냅니다.

네임스페이스:   System.Threading
어셈블리:  mscorlib(mscorlib.dll에 있음)

System.Object
  System.Threading.CancellationTokenSource

[ComVisibleAttribute(false)]
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
public class CancellationTokenSource : IDisposable

이름설명
System_CAPS_pubmethodCancellationTokenSource()

CancellationTokenSource 클래스의 새 인스턴스를 초기화합니다.

System_CAPS_pubmethodCancellationTokenSource(Int32)

지정한 지연(밀리초) 후에 취소되는 CancellationTokenSource의 새 인스턴스를 초기화합니다.

System_CAPS_pubmethodCancellationTokenSource(TimeSpan)

지정한 시간 범위 후에 취소되는 CancellationTokenSource의 새 인스턴스를 초기화합니다.

이름설명
System_CAPS_pubpropertyIsCancellationRequested

CancellationTokenSource의 취소가 요청되었는지 여부를 가져옵니다.

System_CAPS_pubpropertyToken

CancellationToken와 연결된 CancellationTokenSource를 가져옵니다.

이름설명
System_CAPS_pubmethodCancel()

취소 요청을 전달합니다.

System_CAPS_pubmethodCancel(Boolean)

취소 요청을 전달하고 나머지 콜백과 취소 가능한 작업을 처리해야 하는지를 지정합니다.

System_CAPS_pubmethodCancelAfter(Int32)

지정한 시간(밀리초) 후에 이 CancellationTokenSource를 취소하는 작업을 예약합니다.

System_CAPS_pubmethodCancelAfter(TimeSpan)

지정한 시간 범위 후에 이 CancellationTokenSource를 취소하는 작업을 예약합니다.

System_CAPS_pubmethodSystem_CAPS_staticCreateLinkedTokenSource(CancellationToken, CancellationToken)

취소된 상태인 원본 토큰이 있는 경우 취소된 상태가 되는 CancellationTokenSource를 만듭니다.

System_CAPS_pubmethodSystem_CAPS_staticCreateLinkedTokenSource(CancellationToken[])

지정한 배열에 취소된 상태인 원본 토큰이 있는 경우 취소된 상태가 되는 CancellationTokenSource를 만듭니다.

System_CAPS_pubmethodDispose()

CancellationTokenSource 클래스의 현재 인스턴스에서 사용하는 모든 리소스를 해제합니다.

System_CAPS_protmethodDispose(Boolean)

CancellationTokenSource 클래스에 사용되는 관리되지 않는 리소스를 해제하고, 필요에 따라 관리되는 리소스를 해제합니다.

System_CAPS_pubmethodEquals(Object)

지정한 개체가 현재 개체와 같은지 여부를 확인합니다. (Object에서 상속됨)

System_CAPS_protmethodFinalize()

개체가 가비지 수집자에서 회수되기 전에, 해당 개체에서 리소스를 해제하고 다른 정리 작업을 수행할 수 있게 합니다. (Object에서 상속됨)

System_CAPS_pubmethodGetHashCode()

기본 해시 함수로 작동합니다.(Object에서 상속됨)

System_CAPS_pubmethodGetType()

현재 인스턴스의 Type을 가져옵니다.(Object에서 상속됨)

System_CAPS_protmethodMemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.(Object에서 상속됨)

System_CAPS_pubmethodToString()

현재 개체를 나타내는 문자열을 반환합니다.(Object에서 상속됨)

Starting with the net_v40_long, the .NET Framework uses a unified model for cooperative cancellation of asynchronous or long-running synchronous operations that involves two objects:

  • A T:System.Threading.CancellationTokenSource object, which provides a cancellation token through its P:System.Threading.CancellationTokenSource.Token property and sends a cancellation message by calling its M:System.Threading.CancellationTokenSource.Cancel or M:System.Threading.CancellationTokenSource.CancelAfter(System.Int32) method.

  • A T:System.Threading.CancellationToken object, which indicates whether cancellation is requested.

The general pattern for implementing the cooperative cancellation model is:

  • Instantiate a T:System.Threading.CancellationTokenSource object, which manages and sends cancellation notification to the individual cancellation tokens.

  • Pass the token returned by the P:System.Threading.CancellationTokenSource.Token property to each task or thread that listens for cancellation.

  • Call the P:System.Threading.CancellationToken.IsCancellationRequested method from operations that receive the cancellation token. Provide a mechanism for each task or thread to respond to a cancellation request. Whether you choose to cancel an operation, and exactly how you do it, depends on your application logic.

  • Call the M:System.Threading.CancellationTokenSource.Cancel(System.Boolean) method to provide notification of cancellation. This sets the P:System.Threading.CancellationToken.IsCancellationRequested property on every copy of the cancellation token to true.

  • Call the M:System.Threading.CancellationTokenSource.Dispose method when you are finished with the T:System.Threading.CancellationTokenSource object.

For more information, see Cancellation.

System_CAPS_important중요

This type implements the T:System.IDisposable interface. When you have finished using an instance of the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its M:System.IDisposable.Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the “Using an Object that Implements IDisposable” section in the T:System.IDisposable interface topic.

The following example uses a random number generator to emulate a data collection application that reads 10 integral values from eleven different instruments. 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.

To handle the possible cancellation of the operation, the example instantiates a T:System.Threading.CancellationTokenSource object that generates a cancellation token which is passed to a T:System.Threading.Tasks.TaskFactory object. The T:System.Threading.Tasks.TaskFactory object in turn passes the cancellation token to each of the tasks responsible for collecting readings for a particular instrument. The M:System.Threading.Tasks.TaskFactory.ContinueWhenAll``2(System.Threading.Tasks.Task{``0}[],System.Func{System.Threading.Tasks.Task{``0}[],``1},System.Threading.CancellationToken) method is called to ensure that the mean is computed only after all readings have been gathered successfully. If a task has not because it has been cancelled, the call to the M:System.Threading.Tasks.TaskFactory.ContinueWhenAll``2(System.Threading.Tasks.Task{``0}[],System.Func{System.Threading.Tasks.Task{``0}[],``1},System.Threading.CancellationToken) 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.

유니버설 Windows 플랫폼
8 이후 사용 가능
.NET Framework
4.0 이후 사용 가능
이식 가능한 클래스 라이브러리
이식 가능한 .NET 플랫폼 에서 지원됨
Silverlight
5.0 이후 사용 가능
Windows Phone Silverlight
8.0 이후 사용 가능
Windows Phone
8.1 이후 사용 가능

All public and protected members of T:System.Threading.CancellationTokenSource are thread-safe and may be used concurrently from multiple threads, with the exception of M:System.Threading.CancellationTokenSource.Dispose, which must only be used when all other operations on the T:System.Threading.CancellationTokenSource object have completed.

맨 위로 이동
표시: