Introduction
In modern .NET Core applications, especially those that involve long-running tasks, asynchronous operations, or HTTP requests, there is often a need to cancel an operation before it completes. This is where the CancellationToken comes into play.
In this article, we’ll explore what CancellationToken is, why it’s needed, how it works, and how to use it with a simple example.
What is a CancellationToken?
A CancellationToken in .NET Core is a mechanism to signal that an operation should be canceled. It allows tasks, loops, or asynchronous operations to cooperatively stop execution when requested.
Think of it as a “stop sign” you can pass to an operation. The operation checks this token periodically, and stops gracefully if cancellation is requested.
Why Do We Need CancellationToken?
Imagine a scenario where your application is performing a long-running task, like:
Downloading a large file
Processing millions of records
Calling an external API that might hang
Without a cancellation mechanism:
The operation will run until completion, wasting resources.
Users cannot stop operations if they change their mind.
It could lead to unresponsive applications.
CancellationToken solves this by allowing controlled, cooperative cancellation.
Key Components
CancellationTokenSource (CTS)
Generates a
CancellationToken.Signals when cancellation is requested.
CancellationToken
Passed to the task or method that needs to support cancellation.
Checked periodically to stop execution.
How to Use CancellationToken
Step 1: Create a CancellationTokenSource
var cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
Step 2: Pass the Token to an Operation
async Task DoWorkAsync(CancellationToken cancellationToken)
{
for (int i = 0; i < 10; i++)
{
// Check if cancellation has been requested
if (cancellationToken.IsCancellationRequested)
{
Console.WriteLine("Operation canceled!");
return;
}
Console.WriteLine($"Working... {i + 1}");
await Task.Delay(1000); // Simulate work
}
Console.WriteLine("Work completed successfully!");
}Step 3: Request Cancellation
// Start the task
var task = DoWorkAsync(token);
// Cancel after 3 seconds
cts.CancelAfter(3000);
await task;Output:
Working... 1
Working... 2
Working... 3
Operation canceled!Notice how the task stops gracefully when cancellation is requested.

Join the conversation! Your thoughts help the community grow.