Polly with .NET 6, Part 5 - Using a Cancellation Token
Download full source code.
Want to learn more about Polly? Check out my Pluralsight course on it.
This is a quick post to show you how to use Polly with .NET 6 to make a web service request that can be canceled if it is taking too long.
With the cancellation token, the current request will be canceled, and any remaining retries will be abandoned.
I am reusing code from earlier posts on Polly and .NET 6, so I not going to explain everything in detail.
The retry policy
I have a simple retry policy that will retry a request up to 3 times.
builder.Services.AddSingleton<IAsyncPolicy<HttpResponseMessage>>(
Policy.HandleResult<HttpResponseMessage>(
r => !r.IsSuccessStatusCode).RetryAsync(3));
An endpoint that fails
Here is a simple endpoint that fails 75% of the time, and responds slowly (note the one second delay on line 7).
|
|
An endpoint that calls the failing endpoint
Here is an endpoint that calls the failing endpoint, and uses the retry policy to retry the request.
It also uses a cancellation token to cancel the request if it takes too long. In this case, the request will be canceled after 3 seconds, any remaining retries will also be abandoned.
The cancellation token is passed to the policy.ExecuteAsync
method on lines 15/16.
|
|
That’s all there is to it.
The attached zip file has the full source code.
Download full source code.