1

I have tried many ways but failed to catch the cancellation exception in task.ContinueWith. Is there anything wrong here:

 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();

The output is :

Cancelled:

which implies the cancellation exception is caught but the exception itself is empty. My question is how to get the cancellation exception here?

Thanks

Derek

derek
  • 9,358
  • 11
  • 53
  • 94
  • Well, if a task is canceled, then because you had canceled it. If a task it is faulted, there could be any reason for and then you need the exception to have a clue. Why do you need the exception when the task is canceled? BTW If there were any exception then you can only expect the OperationCanceledException. Did not make any sense to keep the exception ;o) – Sir Rufo Nov 12 '16 at 21:52
  • Why can't you just use the `t.IsCanceled` test? That seems sufficient. – usr Nov 12 '16 at 22:08

1 Answers1

2

The cancellation exception is not automatically thrown the moment you cancel the CancellationToken, if you will not throw the exception by yourself the task will be canceled but no exception will be thrown, this is why the task Exception property is null.

In order to throw the exception you should use ThrowIfCancellationRequested method inside one of your task actions.

More info about it here.

YuvShap
  • 3,825
  • 2
  • 10
  • 24