c# - HttpClient Parallel Requests Timeout using Task.WhenAll 当一个请求超时

标签 c# task dotnet-httpclient

我使用一个 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.

来源:https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.whenall?view=netframework-4.8

关于c# - HttpClient Parallel Requests Timeout using Task.WhenAll 当一个请求超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56952587/

相关文章:

c# - 如何减少Socket应用程序的C#内存使用率

c# - 在 SelectMany LINQ 中使用索引

c# - Thread.Join 与 Task.Wait

c# - .NET Core - HTTPClient - Ubuntu 20.04 上的 dh key 太小

c# - 比较请求中的属性是否具有相等的值 C#

c# - 在 C# 中,我可以在 Restsharp 中设置一些 httpclienthandler 属性吗?

c# - 数据访问 : Fluent Nhibernate vs ADO. NET 与 Linq to Sql?

c# - 替换 Unity RegisterType<From, To> 与 RegisterType<T> 中的注册类型

android - 在 android.intent.action.USER_PRESENT 上将任务置于最前面

if-statement - OpenMP 任务 if 或 Final