Main menu

Pages

CancellationToken In Asynchronous Programming C#

CancellationToken In Asynchronous Programming C#

What is a CancellationToken in brief?

when we deal with asynchronous programming, this type of programming can take a long time to execute so we need to take control of it which enables us to save resources like  CPU, memory, and thread pool.

also, we need to distinguish between tasks canceled by the owner or canceled due to exceptions like a timeout.




If we look at this photo which came from the official documentation of Microsoft to explain the process briefly starting from propagating cancellationToken with each dependent async operation.

If the owner wants to cancel the request will stop all callback operations and sane resources.

by creating one or more long-running asynchronous operations we need to pass this token to the other operations.

 we need to take care of operations that can be canceled from the owner only like (Object) and no sub or individual operation can cancel itself, it's one-way.

also, this token is valid for one time so if it is marked as canceled we cannot able to use it again.

So from Where cancellation token was generated?

We have in .NET 3 classes 

CancellationTokenSource and CancellationTokenOperationCancelledException classes

CancellationTokenSourceresponsible for providing a cancellation token.

CancellationToken: sent to all async operations which enable us to take control over operations if we want to cancel.

OperationCancelledExceptionthrow an exception if a cancellation request requested in response to it



How we can check if a cancellation request is asked?


in 3 ways :

  -  CancellationToken.IsCancellationRequested

  - CancellationToken

.ThrowIfCancellationRequested();

  - CancellationToken.Register(() =>
     {
    webClient .CancelAsync();
    );








this method allows registering a callback method if the operation is blocked which we cannot check if a cancellation request raised or not



How to distinguish between tasks canceled by the owner or canceled due to exceptions like a timeout?

by registering multiple cancellation tokens together in the photo down below


Handling cancellation exceptions 

References:


Comments