In C# asynchronous programming, Tasks allow you to perform operations without blocking the main thread, which improves performance and responsiveness of the applications. However, sometimes you may need to cancel an ongoing task due to some programming need, this is where Task Cancellation come into play.
The Task Parallel Library (TPL) provides a reliable and robust mechanism to cancel tasks gracefully in C#.
Key Components of Task Cancellation in C#
Task cancellation involves several key components in C#:
- CancellationTokenSource (CTS): This is the main component behind the cancellation process. It generates a cancellation token that can be passed to Tasks.
- CancellationToken: This token is obtained from CancellationTokenSource and passed to tasks or methods that should support cancellation.
What is CancellationTokenSource?
CancellationTokenSource (known as CTS) generates CancellationToken objects and signals the token when it is cancelled.
Essentially, the CancellationTokenSource acts as a controller, when you want to cancel a task, you call the Cancel method on the CancellationTokenSource, which then signals the CancellationToken.
|
1 2 |
CancellationTokenSource cancellationTknSource= new CancellationTokenSource(); CancellationToken cancellatonTkn = cts.Token; |
What is a Cancellation Token?
A CancellationToken in C# is part of System.Threading namespace enables polling for a cancellation request, this token works in coordination with CancellationTokenSource.
|
1 2 |
CancellationTokenSource cancellationTknSource= new CancellationTokenSource(); CancellationToken cancellatonTkn = cts.Token; |
How to Cancel Tasks in C# using Cancellation Token?
Let’s walk through an example to understand step by step process of cancelling a task using cancellation tokens in C#.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
using System; using System.Threading; using System.Threading.Tasks; namespace TaskCancellationInCSharp { internal class Program { static void Main(string[] args) { //Cancellation Token source object creation CancellationTokenSource cancellationTknSource = new CancellationTokenSource(); //Create the token object and assign the Cancellation token to it CancellationToken cancellationTkn = cancellationTknSource.Token; Console.WriteLine("PrintEvenNumbers Operation started.."); Console.WriteLine("Print Even Numbers"); //Pass the Cancellation token to the task Task task = Task.Run(() => { PrintEvenNumbers(cancellationTkn); }); //Do a 15 millisec delay before calling the Cancel method to stop the task. Console.WriteLine("Main thread sleeps for 15 milli sec."); Thread.Sleep(15); Console.WriteLine("Initiate PrintEvenNumbers Task Cancellation."); //Call the tokensource cancel method to signal the token to cancel the task. cancellationTknSource.Cancel(); } private static void PrintEvenNumbers(CancellationToken cancellationTkn) { int i = 0; while(i != int.MaxValue ) { //Check if task cancellation signal has been triggered. if(!cancellationTkn.IsCancellationRequested) { if (i % 2 == 0) Console.WriteLine("{0}", i); } else { Console.WriteLine("Task Cancelled !!"); return; } i++; } } } } |
In the above example.
- We create a CancellationTokenSource object.
|
1 |
CancellationTokenSource cancellationTknSource = new CancellationTokenSource(); |
- Create the token object and assign the Cancellation token to it.
|
1 |
CancellationToken cancellationTkn = cancellationTknSource.Token; |
- Pass the Cancellation token to the Task PrintEvenNumbers
|
1 |
Task task = Task.Run(() => { PrintEvenNumbers(cancellationTkn); }); |
- Finally invoke the CancellationTokenSource cancel method to signal the token to cancel the task.
|
1 |
cancellationTknSource.Cancel(); |
When we run the above example following output generated.

The program starts printing the Even Numbers in the console output and once the Cancellation initiated then the Task just exited gracefully.
Conclusion
Cancellation tokens are a powerful feature in C# that allow developers to manage tasks more effectively. It improves the responsiveness and resource management of your applications, especially in scenarios that involves long-running operations.
Thanks for visiting 🙂 Please have a look at some of my other blogs on similar topic and provide your valuable feedback or comments.
