首页 > 解决方案 > HttpClient 卡在异步任务上

问题描述

我有一个 HttpClient,我正在使用以下代码根据远程服务器上的文件提取流。当线程到达第三个等待时,它会在那里暂停很长时间。如果文件的大小妨碍它们分别为 33347 kb、123665 kb 和 178688 kb,但我怀疑是这种情况,因为最后两个大小相似。

// a property in a class
private HttpClient HttpClient { get; set; } = new HttpClient() { Timeout = TimeSpan.FromMilliseconds(-1) };

// in a function in that class
using Stream stationsStream = await HttpClient.GetStreamAsync("https://eddb.io/archive/v6/stations.jsonl");
using Stream systemsStream = await HttpClient.GetStreamAsync("https://eddb.io/archive/v6/systems_populated.jsonl");
// always gets stuck on the third await no matter the order.
using Stream listingStream = await HttpClient.GetStreamAsync("https://eddb.io/archive/v6/listings.csv"); 

我没有过多地使用 HttpClient 类,但提出的一些理论是 API 只允许两个连接,或者 HttpClient 只能接受两个。

标签: c#dotnet-httpclient

解决方案


我需要HttpClient用 a创建并将 'HttpClientHandler传递给HttpClientHandler'HttpClient的构造函数,同时将HttpClientHandler'更改MaxConnectionsPerServer为更大的数字。例如:

private HttpClient HttpClient { get; set; } = new HttpClient(Handler) { Timeout = TimeSpan.FromMilliseconds(-1) };
private static HttpClientHandler Handler { get; set; } = new HttpClientHandler() { MaxConnectionsPerServer = 3 };

推荐阅读