In this tutorial we will learn about CancellationToken and how we can use it.
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:
CancellationTokenSource.CancelAfter
can automatically cancel tasks that exceed a specified duration, ensuring that your application remains responsive.CancellationTokenSource
instances together to cancel multiple operations simultaneously, simplifying the coordination of complex tasks.CancellationToken
establishes a standard pattern for task cancellation, making the code easier to understand and maintain.Here’s a simplified example of how
CancellationToken
can be used to cancel an ongoing operation:
csharppublic 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."); } }
When we run this code we found OperationCanceledException is there.
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.
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.
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
csharpusing 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}"); } } }
You can manually cancel the request by calling
Cancel
on the CancellationTokenSource
:
csharpusing 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}"); } } }
CancellationTokenSource
which provides a CancellationToken
.cts.CancelAfter(TimeSpan.FromSeconds(x))
to automatically cancel the request after a specified duration.CancellationToken
to the GetAsync
method.OperationCanceledException
to handle cancellation scenarios.By using a CancellationToken, you can manage and cancel long-running
HttpClient
calls effectively in .NET Core.
Thanks
Copyrights © 2024 letsupdateskills All rights reserved