🔧 Error Fixes
· 1 min read

C#: HttpClient Timeout — How to Fix It


TaskCanceledException: A task was canceled from HttpClient usually means the request timed out (default 100 seconds).

Fix 1: Increase the timeout

var client = new HttpClient {
    Timeout = TimeSpan.FromMinutes(5)
};

Fix 2: Use per-request cancellation tokens

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var response = await client.GetAsync(url, cts.Token);

Fix 3: Distinguish timeout from cancellation

try {
    var response = await client.GetAsync(url, cancellationToken);
} catch (TaskCanceledException ex) when (!cancellationToken.IsCancellationRequested) {
    // This is a timeout, not a user cancellation
    Console.WriteLine("Request timed out");
} catch (TaskCanceledException) {
    // User cancelled the request
    Console.WriteLine("Request cancelled");
}

Fix 4: Use HttpClientFactory

Don’t create HttpClient instances manually in ASP.NET Core. Use IHttpClientFactory to manage lifetimes and configure timeouts per named client:

services.AddHttpClient("slow-api", client => {
    client.Timeout = TimeSpan.FromMinutes(5);
});

Related: C# cheat sheet · C#: ObjectDisposedException fix · Connection Timeout fix