CodexBloom - Programming Q&A Platform

Unhandled TaskCanceledException When Using HttpClient with Polly for Resilience in C# 10

👀 Views: 220 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
c# httpclient polly aspnetcore C#

I tried several approaches but none seem to work... I'm implementing a retry policy using Polly with HttpClient in an ASP.NET Core 6 application, but I'm running into issues when a request times out. Specifically, I'm seeing an `Unhandled TaskCanceledException` that I need to seem to catch properly. My HttpClient setup is using a default timeout of 5 seconds, and I'm trying to configure a retry policy for transient failures. Here's the relevant code: ```csharp services.AddHttpClient<IMyService, MyService>() .AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)))) .ConfigureHttpClient(client => { client.Timeout = TimeSpan.FromSeconds(5); }); ``` When I make a request to a slow external API, the request times out after 5 seconds, but instead of retrying, I get the following behavior message: ``` Unhandled TaskCanceledException: The operation was canceled. ``` I've confirmed that `IMyService` is properly set up to call the external API, and I'm invoking it like this: ```csharp var result = await myService.GetDataAsync(); ``` I expected Polly to handle the timeout and retry the request, but it appears that the `TaskCanceledException` is causing the operation to unexpected result outright. How can I modify my code to catch this exception and ensure that Polly retries the request as intended? Is there a specific way to handle timeouts with Polly? Any insights would be greatly appreciated. For context: I'm using C# on Windows. Is there a better approach?