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:
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)
CancellationToken
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.
Use Cases for CancellationToken
HTTP Requests
Cancel an API call if it takes too long or the client disconnects.
Background Services
Stop background tasks in ASP.NET Core when the application shuts down.
Long-Running Operations
Allow users to cancel processes like file uploads, downloads, or heavy calculations.
Best Practices
Always check IsCancellationRequested
Inside loops or long operations.
Throw OperationCanceledException for Tasks
In tasks, you can throw OperationCanceledException when canceled.
This ensures proper task cancellation and status handling.
cancellationToken.ThrowIfCancellationRequested();
Pass the token to async methods that support it
Many .NET Core methods like Task.Delay or HttpClient.SendAsync accept CancellationToken.
Dispose CancellationTokenSource
After use, dispose to free resources:
cts.Dispose();
Real-World Example: Cancel HTTP Request
using var cts = new CancellationTokenSource();
var client = new HttpClient();
try
{
cts.CancelAfter(2000); // cancel after 2 seconds
HttpResponseMessage response = await client.GetAsync("https://example.com/largefile", cts.Token);
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
catch (OperationCanceledException)
{
Console.WriteLine("HTTP request was canceled.");
}
This pattern is especially useful in web applications where users may navigate away or abort a request.
Advantages
| Advantage | |
|---|
| Graceful Cancellation | Tasks stop safely without leaving the system in an inconsistent state. |
| Better Resource Management | Prevent unnecessary CPU, memory, or network usage. |
| Improved User Experience | Users can cancel long-running operations instead of waiting. |
| Integrates with Async/Await | Works seamlessly with modern asynchronous programming patterns. |
Conclusion
In this article we have seen how CancellationTokenis a powerful and essential tool for .NET Core developers. Whether you are building background services, API calls, or long-running tasks, it allows you to control execution, manage resources efficiently, and improve user experience.
By learning and implementing CancellationToken in your applications, you can build responsive, resilient, and professional-grade software. Hope you find this helpful. Happy Reading!