dotnet
networking
ai_generated
true
System.Threading.Tasks.TaskCanceledException: A task was canceled.
ID: dotnet/taskcanceledexception
85%Fix Rate
88%Confidence
60Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 8 | active | — | — | — |
Root Cause
TaskCanceledException in HTTP contexts is typically a timeout, not an explicit cancellation. HttpClient's default timeout is 100 seconds. Common in slow APIs, large file downloads, or overloaded servers. Fix by increasing timeout, optimizing the request, or adding proper cancellation handling.
genericWorkarounds
-
88% success Set an appropriate HttpClient.Timeout and distinguish between timeout and cancellation
Set a reasonable timeout: httpClient.Timeout = TimeSpan.FromSeconds(30). To distinguish timeout from user cancellation, check the inner exception: catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException) handles timeouts, while catch (TaskCanceledException ex) when (ex.CancellationToken == userToken) handles explicit cancellation
-
85% success Use CancellationTokenSource with per-request timeouts
Create per-request timeouts: using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); var response = await httpClient.GetAsync(url, cts.Token). This allows different timeouts per endpoint while keeping the HttpClient instance reusable
Dead Ends
Common approaches that don't work:
-
Setting HttpClient.Timeout to Timeout.InfiniteTimeSpan
75% fail
Removes the safety net against hanging requests; if the server never responds, the client thread/connection is blocked forever, leading to resource exhaustion and application hangs under load
-
Catching TaskCanceledException and immediately retrying without backoff
70% fail
If the server is overloaded or slow, immediate retries add more load and make the problem worse. Creates a retry storm that can cascade into full service outage
Error Chain
Frequently confused with: