I have followed the example here and here to handle timeouts successfully with the C# HttpClient but I just can't make it work!
var urls = new List<string> { "/success", "/willtimeout", "/success" };
var baseAddress = "http://endpoint";
var httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 0, 30);
httpClient.BaseAddress = new Uri(baseAddress);
foreach (var url in urls)
{
try
{
var cs = CancellationTokenSource.CreateLinkedTokenSource(CancellationToken.None);
cs.CancelAfter(new TimeSpan(0, 0, 3));
var result = await httpClient.GetAsync(urls, cs.Token);
Console.WriteLine("Success");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
This code will print
Success
A task was canceled.
A task was canceled.
How can I make this work properly without creating a new HttpClient every time?