As of .NET 5, the implementation has changed. HttpClient
still throws a TaskCanceledException
, but now wraps a TimeoutException
as InnerException
. So you can easily check whether a request was canceled or timed out (code sample copied from linked blog post):
try
{
using var response = await _client.GetAsync("http://localhost:5001/sleepFor?seconds=100");
}
// Filter by InnerException.
catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
{
// Handle timeout.
Console.WriteLine("Timed out: "+ ex.Message);
}
catch (TaskCanceledException ex)
{
// Handle cancellation.
Console.WriteLine("Canceled: " + ex.Message);
}