简体   繁体   English

取消任务后,继续任务不执行

[英]Continuation Task does not execute when Task is cancelled

The idea : create a Task that prints an increasing number of asterisks. 这个想法 :创建一个Task ,打印越来越多的星号。 When the user presses Enter , the Task prints 10 asterisks and then stops. 当用户按下EnterTask打印10个星号,然后停止。

The code : 代码

namespace CancellingLongRunningTasks
{
    using System;
    using System.Threading;
    using System.Threading.Tasks;

    class Program
    {
        static void Main()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var token = cancellationTokenSource.Token;

            Task task = Task.Run(() =>
            {
                int count = 1;
                while (!token.IsCancellationRequested)
                {
                    Console.WriteLine(new string('*', count));
                    Thread.Sleep(1000);
                    count++;
                }
            }, token).ContinueWith(
                parent =>
                {
                    var count = 10;
                    while (count > 0)
                    {
                        Console.WriteLine(new string('*', count));
                        Thread.Sleep(1000);
                        count--;
                    }
                }, TaskContinuationOptions.OnlyOnCanceled);

            Console.WriteLine("Press enter to stop the task.");

            if (Console.ReadLine().Contains(Environment.NewLine))
            {
                cancellationTokenSource.Cancel();
                task.Wait();
            }
        }
    }
}

The question : why isn't my continuation task executed? 问题 :为什么我的继续任务没有执行?

It isn't being executed because you're not actively cancelling the Task , only checking if a cancellation was requested. 由于您没有主动取消Task ,因此未执行该Task ,仅检查是否请求取消。 Use CancellationToken.ThrowIfCancellationRequested which throws an OperationCanceledException and will transform the Task into a cancelled state or simply throw the exception with the corresponding token: 使用CancellationToken.ThrowIfCancellationRequested ,它引发OperationCanceledException并将Task转换为取消状态,或者简单地抛出带有相应令牌的异常:

Task task = Task.Run(() =>
{
      int count = 1;
      while (!token.IsCancellationRequested)
      {
           Console.WriteLine(new string('*', count));
           Thread.Sleep(1000);
           count++;
       }
       token.ThrowIfCancellationRequested();
 }, token)

Which is equivalent to: 等效于:

Task task = Task.Run(() =>
{
      int count = 1;
      while (!token.IsCancellationRequested)
      {
           Console.WriteLine(new string('*', count));
           Thread.Sleep(1000);
           count++;
       }
       throw new OperationCanceledException(token);
 }, token)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM