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

时间:2016-11-12 21:26:17

标签: c# 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();

输出结果为:

  

取消:

表示捕获了取消异常,但异常本身为空。我的问题是如何在这里获得取消例外?

由于

德里克

1 个答案:

答案 0 :(得分:1)

取消CancellationToken时不会自动抛出取消异常,如果您不自行抛出异常,任务将被取消但不会抛出异常,这就是任务Exception属性为null的原因。 />

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

有关它的更多信息here