C#:如何在 task.continuewith 中捕获取消异常

C#: How to catch cancellation exception in task.continuewith

我试了很多方法都没有捕捉到task.ContinueWith中的取消异常。这里有什么问题吗:

 CancellationTokenSource tokenSource = new CancellationTokenSource();
 Task task = new Task( ()=> { Thread.Sleep(1000); Console.WriteLine("in task!"); }, tokenSource.Token);

 task.Start();
 tokenSource.Cancel();
 task.ContinueWith(t =>
 {
      if(t.IsCanceled)
      {
           AggregateException e = t.Exception; 
           if(e == null) // is true
                Console.WriteLine("Cancelled: ");
      }
 });

 Console.Read();

输出为:

Cancelled:

这意味着捕获了取消异常,但异常本身是空的。我的问题是这里如何获取取消异常?

谢谢

德里克

取消异常不会在你取消CancellationToken的时候自动抛出,如果你自己不抛出异常任务会被取消但不会抛出异常,这就是任务异常属性 为空。

为了抛出异常,您应该在任务操作之一中使用 ThrowIfCancellationRequested 方法。

更多信息here