CodexBloom - Programming Q&A Platform

C# HttpClient with Polly for Retry Logic - Getting Unhandled Task Exception on Cancellation

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
c# httpclient polly cancellation-token C#

This might be a silly question, but I'm testing a new approach and I'm currently implementing an API client using `HttpClient` along with Polly for retry logic in my .NET 5 application... Everything works as expected until I try to cancel the request using a `CancellationToken`. When the token is triggered, I receive an `Unhandled Task Exception` which leads to an application crash. I have set up my HttpClient like this: ```csharp var httpClient = new HttpClient(); var policy = Policy.Handle<HttpRequestException>() .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))); var cancellationTokenSource = new CancellationTokenSource(); try { var response = await policy.ExecuteAsync(async token => { cancellationTokenSource.Token.ThrowIfCancellationRequested(); return await httpClient.GetAsync("https://example.com/api/data", token); }, cancellationTokenSource.Token); // Process response } catch (OperationCanceledException) { // Handle cancellation } catch (Exception ex) { // Log and handle other exceptions Console.WriteLine(ex.Message); } ``` I have ensured that I pass the `cancellationToken` to both `ExecuteAsync` and `GetAsync`, but when the cancellation is triggered, the method still throws an `AggregateException`. The inner exception indicates that the `HttpRequestException` was thrown, which is confusing because I expected to handle the cancellation gracefully. I've tried surrounding the `ExecuteAsync` call with a try/catch block, but I still encounter the same issue. Is there a recommended way to handle task cancellation in this scenario without running into unhandled exceptions? I'm on macOS using the latest version of C#. I appreciate any insights! Thanks in advance!