×
Get in touch

Get in touch with Binary

Binary Studio website uses cookies to enhance your browsing experience. By continuing to use our site, you agree to our Privacy Policy and use of cookies.

Learn more more arrow
Agree
Saveliy Bondini .NET Developer 23.10.2015

Task cancellation in C# and things you should know about it


The task mechanism in C# is a powerful beast in the area of parallel and concurrent programming. Controlling this beast may take lots of effort and pain. In this article we will discover why task cancellation can be so important and how it can be used in .NET 6.

How do we control

Why should we control the execution flow of the tasks? One reason is business logic or algorithm requirements, such as user request cancellation. Another reason comes from the idea that there should be no unobserved tasks. Such tasks may hold thread pool and CPU resources and therefore be dangerous. Last but not least is the ability to differentiate being cancelled by manually thrown exception or failing by any other exception.

Just for this .NET provides us with two classes:

  • CancellationTokenSource – an object responsible for creating a cancellation token and sending a cancellation request to all copies of that token.
  • CancellationToken – a structure used by listeners to monitor token current state.

How do we pass token

First of all, we should somehow make a task to use created token. One way is to pass it as an argument to the method responsible for creating the task.

Another way is to pass it as parameter to TaskFactory constructor, or add id later to CancellationToken property.

With such an approach, the token is only checked at the very beginning, before starting the execution of the lambda expression. If a token is cancelled then the task is also put in cancelled mode. In examples above the message won’t be printed because the token had been cancelled before the task was created.

But what if we need to stop task execution at a particular moment? Then you should observe the cancellation token state manually inside the task delegate. There are generally two ways for passing token inside task delegate.

The first way is to make the token variable visible by task delegate. It can be accomplished by using a class field, property or even capturing variable within a method.

The second way is to pass the token as state object and downcast it inside task delegate.

How do we observe token

Now when we know how to access token inside a task, it is time to become acquainted with how we can observe token state. You can observe it in three ways: by polling, using callback registration and via wait handle.

1. By polling – periodically check IsCancellationRequested property

2. By periodically checking if token.IsCancellationRequested.

3. Callback registration – provide a callback that would be executed right after cancellation is requested

4. Waiting for the wait handle provided by CancellationToken

You can also observe multiple tokens simultaneously, by creating a linked token source that can join multiple tokens into one.

How do we cancel

We already know how to pass and observe tokens. What is left is how we send the cancellation request. For canceling, we use CancellationTokenSource object. Cancellation request may be direct or deferred.

When we use the Cancel method directly, it implicitly calls all registered callbacks on the current thread. If callbacks throw exceptions, they are wrapped in AggregateException object that will be propagated then to the caller.

Since callbacks are called one by one, optional boolean argument for Cancel method lets you specify behavior upon encountering an exception in any of the registered callbacks.

If the argument is true then the exception will immediately propagate out of the call to Cancel, preventing the remaining callbacks from executing.

If the argument is false, all registered callbacks will be executed with all thrown exceptions wrapped into the AggregateException.

After detecting cancellation request inside a task, common approach is to do some cleanup and throw OperationCanceledException object, to put the task in a cancelled state.

Conclusion

The task cancellation mechanism is an easy and useful tool for controlling task execution flow. It is a part of big .NET ecosystem, therefore its usage in most cases is more preferable than some custom solutions. Even if you don’t want to implement your own cancellation logic it’s a good approach to pass CancellationToken to all async methods that support cancellation (i.e HttpClient.GetAsync() or DbSet.FindAsync()).