方法: タスクとその子を取り消すHow to: Cancel a Task and Its Children

以下の例では、次のタスクを実行する方法を説明します。These examples show how to perform the following tasks:

  1. 取り消すことができるタスクを作成し、開始します。Create and start a cancelable task.

  2. キャンセル トークンをユーザー デリゲートに渡し、必要に応じてタスク インスタンスにも渡します。Pass a cancellation token to your user delegate and optionally to the task instance.

  3. ユーザー デリゲート内のキャンセル要求を確認し、これに応答します。Notice and respond to the cancellation request in your user delegate.

  4. 必要に応じて、タスクが取り消された呼び出し元のスレッドを確認します。Optionally notice on the calling thread that the task was canceled.

呼び出し元のスレッドは、タスクを強制終了せず、キャンセルが要求されたことを通知するだけです。The calling thread does not forcibly end the task; it only signals that cancellation is requested. タスクが既に実行中である場合、ユーザー デリゲートが要求を確認して適切に応答します。If the task is already running, it is up to the user delegate to notice the request and respond appropriately. タスクを実行する前にキャンセルが要求された場合、ユーザー デリゲートは実行されず、タスク オブジェクトは Canceled 状態に遷移します。If cancellation is requested before the task runs, then the user delegate is never executed and the task object transitions into the Canceled state.

Example

次の例は、キャンセル要求に応答して Task およびその子を終了する方法を示しています。This example shows how to terminate a Task and its children in response to a cancellation request. また、ユーザー デリゲートが TaskCanceledException をスローして終了した場合、タスクの終了を待つために、呼び出し元スレッドが必要に応じて Wait メソッドまたは WaitAll メソッドを使用できることも示しています。It also shows that when a user delegate terminates by throwing a TaskCanceledException, the calling thread can optionally use the Wait method or WaitAll method to wait for the tasks to finish. この例では try/catch ブロックを使用して、呼び出し元スレッドで例外を処理する必要があります。In this case, you must use a try/catch block to handle the exceptions on the calling thread.

using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var tokenSource = new CancellationTokenSource();
      var token = tokenSource.Token;

      // Store references to the tasks so that we can wait on them and  
      // observe their status after cancellation. 
      Task t;
      var tasks = new ConcurrentBag<Task>();

      Console.WriteLine("Press any key to begin tasks...");
      Console.ReadKey(true);
      Console.WriteLine("To terminate the example, press 'c' to cancel and exit...");
      Console.WriteLine();
        
      // Request cancellation of a single task when the token source is canceled. 
      // Pass the token to the user delegate, and also to the task so it can  
      // handle the exception correctly.
      t = Task.Factory.StartNew( () => DoSomeWork(1, token), token);
      Console.WriteLine("Task {0} executing", t.Id);
      tasks.Add(t);

      // Request cancellation of a task and its children. Note the token is passed 
      // to (1) the user delegate and (2) as the second argument to StartNew, so  
      // that the task instance can correctly handle the OperationCanceledException.
      t = Task.Factory.StartNew( () => {
                                     // Create some cancelable child tasks.  
                                     Task tc;
                                     for (int i = 3; i <= 10; i++) {
                                        // For each child task, pass the same token 
                                        // to each user delegate and to StartNew.
                                        tc = Task.Factory.StartNew( iteration => DoSomeWork((int)iteration, token), i, token);
                                        Console.WriteLine("Task {0} executing", tc.Id);
                                        tasks.Add(tc);
                                        // Pass the same token again to do work on the parent task.  
                                        // All will be signaled by the call to tokenSource.Cancel below.
                                        DoSomeWork(2, token);
                                     } 
                                  }, 
                                  token);
                                           
        Console.WriteLine("Task {0} executing", t.Id);
        tasks.Add(t);

        // Request cancellation from the UI thread. 
        char ch = Console.ReadKey().KeyChar;
        if (ch == 'c'|| ch == 'C' ) {
            tokenSource.Cancel();
            Console.WriteLine("\nTask cancellation requested.");

            // Optional: Observe the change in the Status property on the task. 
            // It is not necessary to wait on tasks that have canceled. However, 
            // if you do wait, you must enclose the call in a try-catch block to 
            // catch the TaskCanceledExceptions that are thrown. If you do  
            // not wait, no exception is thrown if the token that was passed to the  
            // StartNew method is the same token that requested the cancellation. 
        } 

        try {
            Task.WaitAll(tasks.ToArray());
        }
        catch (AggregateException e) {
           Console.WriteLine("\nAggregateException thrown with the following inner exceptions:");
           // Display information about each exception. 
           foreach (var v in e.InnerExceptions) {
              if (v is TaskCanceledException)
                 Console.WriteLine("   TaskCanceledException: Task {0}", 
                                   ((TaskCanceledException) v).Task.Id);
              else
                 Console.WriteLine("   Exception: {0}", v.GetType().Name);
           } 
           Console.WriteLine();
        }
        finally
        {
           tokenSource.Dispose();
        }

        // Display status of all tasks. 
        foreach (var task in tasks)
            Console.WriteLine("Task {0} status is now {1}", task.Id, task.Status);
   }

   static void DoSomeWork(int taskNum, CancellationToken ct)
   {
      // Was cancellation already requested? 
      if (ct.IsCancellationRequested == true) {
         Console.WriteLine("Task {0} was cancelled before it got started.",
                           taskNum);
         ct.ThrowIfCancellationRequested();
      } 

      int maxIterations = 100;

      // NOTE!!! A "TaskCanceledException was unhandled 
      // by user code" error will be raised here if "Just My Code" 
      // is enabled on your computer. On Express editions JMC is 
      // enabled and cannot be disabled. The exception is benign. 
      // Just press F5 to continue executing your code. 
      for (int i = 0; i <= maxIterations; i++) {
         // Do a bit of work. Not too much. 
         var sw = new SpinWait();
         for (int j = 0; j <= 100; j++)
            sw.SpinOnce();

         if (ct.IsCancellationRequested) {
            Console.WriteLine("Task {0} cancelled", taskNum);
            ct.ThrowIfCancellationRequested();
         } 
      } 
   } 
}  
// The example displays output like the following:
//       Press any key to begin tasks...
//    To terminate the example, press 'c' to cancel and exit...
//    
//    Task 1 executing
//    Task 2 executing
//    Task 3 executing
//    Task 4 executing
//    Task 5 executing
//    Task 6 executing
//    Task 7 executing
//    Task 8 executing
//    c
//    Task cancellation requested.
//    Task 2 cancelled
//    Task 7 cancelled
//    
//    AggregateException thrown with the following inner exceptions:
//       TaskCanceledException: Task 2
//       TaskCanceledException: Task 8
//       TaskCanceledException: Task 7
//    
//    Task 2 status is now Canceled
//    Task 1 status is now RanToCompletion
//    Task 8 status is now Canceled
//    Task 7 status is now Canceled
//    Task 6 status is now RanToCompletion
//    Task 5 status is now RanToCompletion
//    Task 4 status is now RanToCompletion
//    Task 3 status is now RanToCompletion
Imports System.Collections.Concurrent
Imports System.Threading
Imports System.Threading.Tasks

Module Example
    Sub Main()
        Dim tokenSource As New CancellationTokenSource()
        Dim token As CancellationToken = tokenSource.Token

        ' Store references to the tasks so that we can wait on them and  
        ' observe their status after cancellation. 
        Dim t As Task
        Dim tasks As New ConcurrentBag(Of Task)()

        Console.WriteLine("Press any key to begin tasks...")
        Console.ReadKey(True)
        Console.WriteLine("To terminate the example, press 'c' to cancel and exit...")
        Console.WriteLine()
        
        ' Request cancellation of a single task when the token source is canceled. 
        ' Pass the token to the user delegate, and also to the task so it can  
        ' handle the exception correctly.
        t = Task.Factory.StartNew(Sub() DoSomeWork(1, token), token)
        Console.WriteLine("Task {0} executing", t.Id)
        tasks.Add(t)

        ' Request cancellation of a task and its children. Note the token is passed 
        ' to (1) the user delegate and (2) as the second argument to StartNew, so  
        ' that the task instance can correctly handle the OperationCanceledException.
        t = Task.Factory.StartNew(Sub() 
                                     ' Create some cancelable child tasks.  
                                     Dim tc As Task
                                     For i As Integer = 3 To 10
                                        ' For each child task, pass the same token 
                                        ' to each user delegate and to StartNew.
                                        tc = Task.Factory.StartNew(Sub(iteration) DoSomeWork(iteration, token), i, token)
                                        Console.WriteLine("Task {0} executing", tc.Id)
                                        tasks.Add(tc)
                                        ' Pass the same token again to do work on the parent task.  
                                        ' All will be signaled by the call to tokenSource.Cancel below.
                                        DoSomeWork(2, token)
                                     Next 
                                  End Sub, 
                                  token)
                                           
        Console.WriteLine("Task {0} executing", t.Id)
        tasks.Add(t)

        ' Request cancellation from the UI thread. 
        Dim ch As Char = Console.ReadKey().KeyChar
        If ch = "c"c Or ch = "C"c Then
            tokenSource.Cancel()
            Console.WriteLine(vbCrLf + "Task cancellation requested.")

            ' Optional: Observe the change in the Status property on the task. 
            ' It is not necessary to wait on tasks that have canceled. However, 
            ' if you do wait, you must enclose the call in a try-catch block to 
            ' catch the TaskCanceledExceptions that are thrown. If you do  
            ' not wait, no exception is thrown if the token that was passed to the  
            ' StartNew method is the same token that requested the cancellation. 
        End If 

        Try
            Task.WaitAll(tasks.ToArray())
        Catch e As AggregateException
           Console.WriteLine()
           Console.WriteLine("AggregateException thrown with the following inner exceptions:")
           ' Display information about each exception. 
           For Each v In e.InnerExceptions
              If TypeOf v Is TaskCanceledException
                 Console.WriteLine("   TaskCanceledException: Task {0}", 
                                   DirectCast(v, TaskCanceledException).Task.Id)
              Else
                 Console.WriteLine("   Exception: {0}", v.GetType().Name)
              End If
           Next 
           Console.WriteLine()
        Finally
           tokenSource.Dispose()
        End Try 

        ' Display status of all tasks. 
        For Each t In tasks
            Console.WriteLine("Task {0} status is now {1}", t.Id, t.Status)
        Next 
    End Sub 

    Sub DoSomeWork(ByVal taskNum As Integer, ByVal ct As CancellationToken)
        ' Was cancellation already requested? 
        If ct.IsCancellationRequested = True Then
            Console.WriteLine("Task {0} was cancelled before it got started.",
                              taskNum)
            ct.ThrowIfCancellationRequested()
        End If 

        Dim maxIterations As Integer = 100

        ' NOTE!!! A "TaskCanceledException was unhandled 
        ' by user code" error will be raised here if "Just My Code" 
        ' is enabled on your computer. On Express editions JMC is 
        ' enabled and cannot be disabled. The exception is benign. 
        ' Just press F5 to continue executing your code. 
        For i As Integer = 0 To maxIterations
            ' Do a bit of work. Not too much. 
            Dim sw As New SpinWait()
            For j As Integer = 0 To 100
                sw.SpinOnce()
            Next
            If ct.IsCancellationRequested Then
                Console.WriteLine("Task {0} cancelled", taskNum)
                ct.ThrowIfCancellationRequested()
            End If 
        Next 
    End Sub 
End Module
' The example displays output like the following:
'    Press any key to begin tasks...
'    To terminate the example, press 'c' to cancel and exit...
'    
'    Task 1 executing
'    Task 2 executing
'    Task 3 executing
'    Task 4 executing
'    Task 5 executing
'    Task 6 executing
'    Task 7 executing
'    Task 8 executing
'    c
'    Task cancellation requested.
'    Task 2 cancelled
'    Task 7 cancelled
'    
'    AggregateException thrown with the following inner exceptions:
'       TaskCanceledException: Task 2
'       TaskCanceledException: Task 8
'       TaskCanceledException: Task 7
'    
'    Task 2 status is now Canceled
'    Task 1 status is now RanToCompletion
'    Task 8 status is now Canceled
'    Task 7 status is now Canceled
'    Task 6 status is now RanToCompletion
'    Task 5 status is now RanToCompletion
'    Task 4 status is now RanToCompletion
'    Task 3 status is now RanToCompletion

System.Threading.Tasks.Task クラスは、System.Threading.CancellationTokenSource の型および System.Threading.CancellationToken の型に基づくキャンセル モデルに完全に統合されています。The System.Threading.Tasks.Task class is fully integrated with the cancellation model that is based on the System.Threading.CancellationTokenSource and System.Threading.CancellationToken types. 詳細については、「マネージド スレッドのキャンセル」と「タスクのキャンセル」を参照してください。For more information, see Cancellation in Managed Threads and Task Cancellation.

関連項目See also