C#

Understanding CancellationToken in .NET

In this tutorial we will learn about CancellationToken and how we can use it.

Why CancellationToken?

In earlier days, when we had time taking operations like time consuming DB calls, time consuming HTTP calls we had no option to cancel it.

Using a CancellationToken in your applications provides several benefits, particularly in improving responsiveness, resource management, and user experience. Here are some key advantages:

1. Improved Responsiveness

  • User Experience: Applications that can cancel long-running tasks quickly respond to user actions, such as canceling a file upload or download, leading to a better user experience.
  • Real-Time Adjustments: Users can adjust their actions (e.g., stopping a search operation) without waiting for the current operation to complete.

2. Resource Management

  • Efficient Use of Resources: Canceling unnecessary operations prevents waste of CPU, memory, and other resources. This is particularly important for server-side applications where resources are shared among many users.
  • Database Connections: In database operations, using CancellationToken can free up database connections that would otherwise be held by long-running queries.

3. Scalability

  • Handling High Load: Applications can handle high loads more gracefully by canceling operations that are no longer needed, thus freeing up resources for new incoming requests.
  • Concurrency Control: Effective cancellation helps manage concurrent tasks, ensuring that resources are allocated to the most critical operations.

4. Error Handling and Stability

  • Graceful Shutdown: When an application needs to shut down or restart, CancellationToken allows for a graceful termination of ongoing operations, reducing the risk of data corruption or inconsistent states.
  • Preventing Deadlocks: By canceling operations that are taking too long, you can reduce the likelihood of deadlocks and other concurrency issues.

5. Timeout Implementation

  • Automatic Timeout: Implementing timeouts using
    CancellationTokenSource.CancelAfter can automatically cancel tasks that exceed a specified duration, ensuring that your application remains responsive.

6. Task Coordination

  • Cooperative Cancellation: CancellationToken allows for cooperative cancellation, where the operation periodically checks the token to see if cancellation is requested, allowing the operation to clean up and terminate gracefully.
  • Linked Cancellation Tokens: You can link multiple
    CancellationTokenSource instances together to cancel multiple operations simultaneously, simplifying the coordination of complex tasks.

7. Simplified Code Maintenance

  • Standard Pattern: Using
    CancellationToken establishes a standard pattern for task cancellation, making the code easier to understand and maintain.
  • Consistent Handling: It provides a consistent way to handle cancellations across different parts of your application, from user-initiated cancellations to automatic timeouts and application shutdowns.

Example Use Cases

  1. Web Applications: Cancel database queries, file uploads/downloads, and API calls that are no longer needed.
  2. Desktop Applications: Allow users to cancel long-running operations like image processing or data analysis.
  3. Mobile Applications: Improve battery life by canceling background operations when they are no longer needed.
  4. Cloud Services: Efficiently manage resources by canceling operations in response to scaling events or maintenance windows.

Code Example

Here’s a simplified example of how

CancellationToken can be used to cancel an ongoing operation:

csharp
public async Task LongRunningOperationAsync(CancellationToken cancellationToken) { for (int i = 0; i < 100; i++) { // Periodically check if cancellation is requested cancellationToken.ThrowIfCancellationRequested(); // Simulate some work await Task.Delay(100); } } public async Task MainAsync() { using var cts = new CancellationTokenSource(); // Cancel the operation after 2 seconds cts.CancelAfter(TimeSpan.FromSeconds(2)); try { await LongRunningOperationAsync(cts.Token); } catch (OperationCanceledException) { Console.WriteLine("Operation was canceled."); } }

Running Code Output

When we run this code we found OperationCanceledException is there.

Cancellation output

Using

CancellationToken provides significant benefits in terms of responsiveness, resource management, and scalability. By implementing it thoughtfully in your applications, you can greatly enhance the overall performance and user experience.

Cancellation of HTTP Calls

We can cancel time-consuming

HttpClient calls using a
CancellationToken. This allows you to abort the request if it takes too long or if some other condition is met.

1. Using
CancellationTokenSource

You can create a

CancellationTokenSource and pass its token to the HttpClient call. You can then cancel the token after a certain timeout or based on some condition.

Consider code below

csharp
using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { using var httpClient = new HttpClient(); using var cts = new CancellationTokenSource(); // Set a timeout for the request cts.CancelAfter(TimeSpan.FromSeconds(10)); // Cancel after 10 seconds try { var response = await httpClient.GetAsync("https://example.com", cts.Token); response.EnsureSuccessStatusCode(); var content = await response.Content.ReadAsStringAsync(); Console.WriteLine(content); } catch (OperationCanceledException) { Console.WriteLine("Request was canceled."); } catch (HttpRequestException e) { Console.WriteLine($"Request error: {e.Message}"); } } }

2. Manually Cancelling the Request

You can manually cancel the request by calling

Cancel on the
CancellationTokenSource:

csharp
using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { using var httpClient = new HttpClient(); using var cts = new CancellationTokenSource(); var task = httpClient.GetAsync("https://example.com", cts.Token); // Simulate some condition to cancel the request Task.Delay(2000).ContinueWith(_ => cts.Cancel()); try { var response = await task; response.EnsureSuccessStatusCode(); var content = await response.Content.ReadAsStringAsync(); Console.WriteLine(content); } catch (OperationCanceledException) { Console.WriteLine("Request was canceled."); } catch (HttpRequestException e) { Console.WriteLine($"Request error: {e.Message}"); } } }

Explanation:

  1. Creating CancellationTokenSource: You create an instance of
    CancellationTokenSource which provides a
    CancellationToken.
  2. Setting Timeout: Use
    cts.CancelAfter(TimeSpan.FromSeconds(x)) to automatically cancel the request after a specified duration.
  3. Passing Token to HttpClient Call: Pass the
    CancellationToken to the
    GetAsync method.
  4. Handling Exceptions: Catch
    OperationCanceledException to handle cancellation scenarios.

By using a CancellationToken, you can manage and cancel long-running

HttpClient calls effectively in .NET Core.

Thanks

line

Copyrights © 2024 letsupdateskills All rights reserved