当一个请求超时时,HttpClient 并行请求超时使用 Task.WhenAll
HttpClient Parallel Requests Timeout using Task.WhenAll when one request times out
我使用一个 httpclient 发出了约 20 个 http get 请求,这个 httpclient 是长期存在的,意味着它没有打包到 using 语句中。由于网络服务通常非常快(响应时间 ~200ms),我将超时设置为 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 Class
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.
我使用一个 httpclient 发出了约 20 个 http get 请求,这个 httpclient 是长期存在的,意味着它没有打包到 using 语句中。由于网络服务通常非常快(响应时间 ~200ms),我将超时设置为 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 Class
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.