derek
derek

Reputation: 10217

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

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

Upvotes: 1

Views: 1837

Answers (1)

YuvShap
YuvShap

Reputation: 3835

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.

Upvotes: 2

Related Questions