我使用一个 httpclient 发出了大约 20 个 http get 请求,这个 httpclient 是长期存在的,意味着它没有打包到 using 语句中。由于 Web 服务通常非常快(响应时间 ~200 毫秒),我将超时设置为 5 秒。
现在我遇到了问题,如果一个请求超时,所有其他请求都会被取消。这是正常行为吗?
这是我用来进行并发调用的代码
public async Task GetAll()
{
await Task.WhenAll(x => x.Select(xx => GetData(xx.Id));
}
调用api的代码:
public async Task GetData(int id)
{
string payload = "";
try
{
var resp = await base.GetAsync($"/apis/v2/getdata/{id}");
if (!resp.IsSuccessStatusCode)
Console.WriteLine("Error");
payload = await resp.Content.ReadAsStringAsync();
Console.WriteLine(payload);
}
catch (System.Exception ex)
{
Console.WriteLine("Error");
}
}
我的 HttpClient 基类
public class MyHttpClient : System.Net.Http.HttpClient
{
public Logger Log { get; set; }
}
如果我按顺序运行任务,一切正常,但是当我并行运行它们并且一个任务超时时,所有其他未完成的任务将被取消。
最佳答案
If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks.
关于c# - HttpClient Parallel Requests Timeout using Task.WhenAll 当一个请求超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56952587/