首页 > 解决方案 > C#:.NET HttpClient 超时太快

问题描述

我有一个很长的 API URL 调用列表,urlList每个调用都返回相当多的 JSON 数据。其中一些需要几毫秒,其他可能需要几分钟才能完成。这就是为什么我将超时设置为 30 分钟。由于某种原因,HttpClient 实例在 5 分钟后超时,我不知道为什么。当我在浏览器窗口或 Postman 中打开相同的 URL 时,需要 8 到 20 分钟,但当我的 C# 代码(见下文)抛出这些异常时,它们最终会加载:

对于某些 URL,我会得到一个 CanceledException:Task CanceledException - System.Threading.Tasks.TaskCanceledException:任务已取消。在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) 在 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() 在 ...

private async Task<string> ProcessUrls(urlList)
{
    string userAndPasswordToken = Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password);
    ServicePointManager.ServerCertificateValidationCallback += this.ValidateRemoteCertificate;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    this.httpclient.DefaultRequestHeaders.Accept.Clear();
    this.httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    this.httpclient.Timeout = TimeSpan.FromMinutes(30);
    this.httpclient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization",$"Basic {userAndPasswordToken}");

    SemaphoreSlim throttler = new SemaphoreSlim(initialCount: 20);
    List<Task> requests = new List<Task>();
    foreach (var url in urlList)
    {
        await throttler.WaitAsync();
        requests.Add(
            Task.Run(async () =>
            {
                try
                {
                    result = await this.httpclient.GetAsync(url);
                }
                finally
                {
                    throttler.Release();
                }
            }
            )
        );
    }
}

更新:我在没有信号量的情况下尝试了同样的事情,仍然发生同样的问题 - 所以我想我可以排除信号量导致问题。

我在这里想念什么?(注意:我访问的 API 不在我的控制之下)

这是一个.NET项目(targetFramework net452),目前在Win10上的VS2019中运行。

标签: c#.nethttprequest

解决方案


推荐阅读