Task.IsCancelled 不起作用 [英] Task.IsCancelled doesn't work

查看:34
本文介绍了Task.IsCancelled 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下示例代码:

static class Program
{
    static void Main()
    {
        var cts = new CancellationTokenSource();

        var task = Task.Factory.StartNew(
            () =>
                {
                    try
                    {
                        Console.WriteLine("Task: Running");
                        Thread.Sleep(5000);
                        Console.WriteLine("Task: ThrowIfCancellationRequested");
                        cts.Token.ThrowIfCancellationRequested();
                        Thread.Sleep(2000);
                        Console.WriteLine("Task: Completed");
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine("Task: " + exception.GetType().Name);
                        throw;
                    }
                }).ContinueWith(t => Console.WriteLine("ContinueWith: cts.IsCancellationRequested = {0}, task.IsCanceled = {1}, task.Exception = {2}", cts.IsCancellationRequested, t.IsCanceled, t.Exception == null ? "null" : t.Exception.GetType().Name));

        Thread.Sleep(1000);

        Console.WriteLine("Main: Cancel");
        cts.Cancel();

        try
        {
            Console.WriteLine("Main: Wait");
            task.Wait();
        }
        catch (Exception exception)
        {
            Console.WriteLine("Main: Catch " + exception.GetType().Name);
        }

        Console.WriteLine("Main: task.IsCanceled = {0}", task.IsCanceled);
        Console.WriteLine("Press any key to exit...");

        Console.ReadLine();
    }
}

输出为:

  • 任务:运行
  • 主要:取消
  • 主要:等待
  • 任务:ThrowIfCancellationRequested
  • 任务:OperationCanceledException
  • ContinueWith:cts.IsCancellationRequested = True,task.IsCanceled = False,task.Exception = AggregateException
  • 主要:task.IsCanceled = False
  • 按任意键退出...

如果我删除ContinueWith,那么输出是:

If I remove ContinueWith, then the output is:

  • 任务:运行
  • 主要:取消
  • 主要:等待
  • 任务:ThrowIfCancellationRequested
  • 任务:OperationCanceledException
  • 主要:捕获聚合异常
  • 主要:task.IsCanceled = False
  • 按任意键退出...

我不明白,为什么 task.IsCanceled 在这两种情况下都返回 false?

I don't understand, why task.IsCanceled returns false in both cases?

为什么只在没有 ContinueWith 的情况下重新抛出异常?

And why exception is rethrown only without ContinueWith?

我想要实现的是一种统一且简单的等待任务完成的方法,以及一个指示任务是否被取消的属性.

What I'm trying to achieve is an uniform and simple way for waiting for task completion and a property that will indicate if task was cancelled or not.

推荐答案

我认为您不是在取消任务本身,而只是从任务中抛出异常.尝试使用 StartNew(Action action,CancellationToken cancellingToken) 而不是 StartNew(Action action).您还可以添加取消令牌作为 ContinueWith 的参数.

I think you are not cancelling the task itself, but just throwing an exception from a task. Try using StartNew(Action action,CancellationToken cancellationToken) instead of StartNew(Action action). You can also add cancellation token as a parameter to ContinueWith.

这篇关于Task.IsCancelled 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆