Understanding Cancellation Tokens in C#

Osama HaiDer
4 min readNov 25, 2023

--

In the fast-paced world of software development, being quick and responsive is crucial. When dealing with tasks that take a long time or happen in the background, C# developers have a powerful tool called CancellationToken. This guide will help you understand what CancellationToken is, how to use it, and why it’s important. We’ll also look at situations where not using it might cause problems. Let’s dive in!

Understanding CancellationToken:

CancellationToken is a feature introduced in .NET to facilitate cooperative cancellation of operations. It provides a mechanism for signaling to other threads or tasks that a cancellation request has been made. This cooperative nature enables ongoing operations to check for cancellation requests and gracefully terminate if needed.

Anatomy of CancellationToken:

At its core, CancellationToken consists of two main components:

  1. CancellationTokenSource:
  • Responsible for creating and controlling the cancellation token.
  • Generates the actual token that is shared among different parts of your application.

2. CancellationToken:

  • Represents the signal for cancellation.
  • Passed to asynchronous or parallel operations to allow them to observe and respond to cancellation requests.

How to Use CancellationToken:

Example with CancellationToken:

Consider an asynchronous API call scenario:

public async Task<IActionResult> FetchDataWithCancellation(CancellationToken cancellationToken)
{
try
{
// Simulate an external API endpoint
var apiUrl = "https://jsonplaceholder.typicode.com/todos/1";

// Create an HttpClient using the factory
using var httpClient = _httpClientFactory.CreateClient();

// Simulate an asynchronous API call with cancellation
var response = await httpClient.GetStringAsync(apiUrl, cancellationToken);

// Process the API response
return Ok(response);
}
catch (HttpRequestException ex)
{
return BadRequest($"API call failed: {ex.Message}");
}
catch (OperationCanceledException)
{
return StatusCode(500, "API call was canceled.");
}
}

Here, CancellationToken is gracefully integrated into an asynchronous API call. The cancellation token is checked within the operation, allowing for a clean and responsive cancellation mechanism.

Example without CancellationToken:

Now, let’s explore a scenario without CancellationToken:

public async Task<IActionResult> FetchDataWithoutCancellation()
{
try
{
// Simulate an external API endpoint
var apiUrl = "https://jsonplaceholder.typicode.com/todos/1";

// Create an HttpClient using the factory
using var httpClient = _httpClientFactory.CreateClient();

// Simulate a non-cancellable asynchronous API call
var response = await httpClient.GetStringAsync(apiUrl);

// Process the API response
return Ok(response);
}
catch (HttpRequestException ex)
{
return BadRequest($"API call failed: {ex.Message}");
}
}

In this example, the absence of CancellationToken might not seem problematic in this simple context. However, in more complex scenarios or applications with frequent user interactions, the lack of cancellation handling could lead to unresponsive behavior.

When to Use CancellationToken:

  • Long-Running Operations:
    CancellationToken is invaluable when dealing with operations that might take a considerable amount of time to complete. By allowing users to interrupt or cancel such operations, you enhance the overall user experience.
  • Parallel Processing:
    In scenarios involving parallel operations, such as parallel loops or Task Parallel Library (TPL) tasks, CancellationToken provides a consistent and reliable way to cancel these parallel tasks gracefully.
  • Asynchronous Operations:
    When making asynchronous calls, especially to external services or APIs, incorporating CancellationToken allows your application to handle cancellations gracefully, preventing unnecessary resource utilization.

Usage and Benefits of CancellationToken:

  • Graceful Cancellation:
    CancellationToken ensures that ongoing operations are terminated gracefully, preventing abrupt disruptions and potential resource leaks.
  • Responsive Applications:
    By incorporating CancellationToken, you enhance the responsiveness of your applications. Users can interrupt time-consuming operations, making the application more user-friendly.
  • Error Handling:
    The OperationCanceledException thrown upon cancellation provides a structured way to handle and log cancellations, facilitating error diagnosis and resolution.
  • Consistent API Design:
    When designing APIs, incorporating CancellationToken provides a consistent pattern for handling cancellations. It aligns with the principles of cooperative cancellation across different parts of your application.

Conclusion:

In conclusion, mastering CancellationToken in C# is an essential skill for any developer aiming to create responsive, user-friendly applications. Understanding its complexities, applying it to various asynchronous scenarios, and recognizing when to employ it will empower you to build software that gracefully responds to user actions. Whether dealing with long-running tasks, parallel processing, or asynchronous calls, CancellationToken ensures that your applications remain robust, efficient, and user-centric. As you navigate the diverse landscape of asynchronous programming, let CancellationToken be your guide to creating a seamless and responsive user experience.

If you found this blog post on CancellationToken in C# insightful, you might want to explore the accompanying GitHub repository for practical examples and additional resources:

👉 [GitHub Repository]

Feel free to fork the repository, open issues, or submit pull requests. Your contributions are welcome!

For more updates, insights, and to connect with me, feel free to follow me on LinkedIn:

🔗 [Connect on LinkedIn]

Let’s stay connected and continue the conversation! 🚀

--

--

Osama HaiDer
Osama HaiDer

Written by Osama HaiDer

SSE at TEO International | .Net | Azure | AWS | Web APIs | C#

No responses yet