My usage scenario: I have a lot of Url links, and I will request them regularly to judge whether the service is normal. And the status of these URLs will be displayed on the client side
Problem: If one of the Urls times out, the other Urls will wait together. How can I handle this situation? such as not blocking other requests after Url1 times out (other urls will return results first).
How to return the results of parallel runs through the API (Or keep returning results)? Let the client display more friendly. such as returning the normal URL result first, and then returning the timeout result after waiting for a timeout.
The following Test1 and Test2 are my two attempts, but none of them have achieved the desired effect.
string[] urls = new string[]
{
"https://localhost:7268/api/Timeout",
"https://www.google.com:81",
"https://url1",
"https://url2"
};
// Get Data
async Task<HttpResponseMessage> HttpRequest2Async(string url, CancellationToken cancellationToken = default)
{
HttpClient httpClient = new HttpClient();
var responseMessage = await httpClient.GetAsync(url, cancellationToken);
return responseMessage;
}
// Test1 When Url1 times out, other Urls behind will wait.
List<HttpResponseMessage> urlResponses = new();
foreach (string url in urls)
{
var responseMessage = await HttpRequest2Async(url, default);
urlResponses.Add(responseMessage);
}
// Test2 As long as there is a Url timeout, all Urls will wait.
var tasks = new List<Task<HttpResponseMessage>>();
foreach (string url in urls)
{
var task = HttpRequest2Async(url, default);
tasks.Add(task);
}
var res = await Task.WhenAll(tasks);
Result:
The Url behind https://localhost:7268/api/Timeout will wait for it to complete before continuing to execute.
All URLs will wait for https://localhost:7268/api/Timeout to complete before returning the result.