Saveliy Bondini.NET Developer

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


Task mechanism in C# is a powerful beast in the area of parallel and asynchrony programming. Controlling this beast may take lots of efforts and pain. .NET Framework 4 introduces a convenient approach for cancellation of asynchronous operations.

How do we control

Why should we control execution flow of the tasks? One reason is business logic or algorithm requirements. Another reason comes from an idea, that there should be no unobserved tasks. Such tasks may hold thread pool and CPU resources and therefore be dangerous.

Just for this .NET provides us with two classes:

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

How do we pass token

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

With such approach token is only checked at the very beginning, before starting execution of task delegate code. If token cancelled then task is also put in canceled mode. In the example above message won’t be printed because token had been canceled before task were created.

But what if we want to stop task execution in particular moment of time? Then you should observe cancellation token state manually inside task delegate. There are generally two ways for passing token inside task delegate.

First way is to make token variable visible by task delegate. It can be accomplished by using global variable or variable capture.

Second way is to pass token as state object and downcast it inside task delegate.

How do we observe token

Now that 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 the three ways: by polling, using callback registration and via wait handle.

1. By polling – periodically check IsCancellationRequested property

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

3. Waiting for wait handle provided by CancellationToken.

You can also observe multiple tokens simultaneously, by creating 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 cancellation request. For cancelling, we use CancellationTokenSource object. Cancellation request may be direct or deferred.

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

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

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

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

After detecting cancellation request inside task, common approach is to throw OperationCanceledException object, to put task in canceled state.

Conclusion

Task cancellation mechanism is an easy and useful tool for controlling task execution flow. It is a part of big .NET Framework ecosystem, therefore its usage in most cases is more preferable than some custom solutions.

 

  • Lais Gomes

    Hi! Very helpful, explained clearly and objectively, thank’s. =)

  • very helpful!

  • Emran Hussain

    If you would call the ThrowIfCancellationRequested() then you should need to check if (token.IsCancellationRequested). Because, notice that, there is an ‘if’ in the method name ThrowIfCancellationRequested(). Therefore, cancellation exception will be thrown ONLY IF the cancellation is requested. checking if (token.IsCancellationRequested) is redundant in this case.

    • Emran Hussain

      Sorry, I missed the “NOT” word in my comment. I meant “you should NOT need to check if (token.IsCancellationRequested)

  • Bang

    Good article. Two examples are missing a space: “newCancellationTokenSource”

  • Genie

    Let me ask a dumb question. Why can’t I just use a simple global boolean variable as a flag as the token? and do something like while(!globalVariable) in the task?

    • Jey

      I guess, it will work 🙂