【发布时间】:2016-10-20 03:31:03
【问题描述】:
我有类似下面的东西
public async Task PostTest()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("abc.com");
var response = await client.PostAsync("/api/call", new StringContent("hello world"));
//do something with response and dispose it.
//NOTE: server is long running, so dispose is not getting called before sending other remaning requests.
}
}
我反过来从一个循环中调用这个方法来快速连续发送大量请求。
根据我对HttpClient 的了解,它将请求与特定的ServicePoint 对象相关联,该对象的默认ConnectionLimit 值为2。由于我的所有请求都针对相同的uri,因此只有一个应该创建ServicePoint 对象,因此将我限制为最多两个并发请求(假设流水线已关闭)。
我在运行时实际看到的是,如果我在“同时”n 次调用我的 PostTest() 方法,我会看到 n 个请求由于服务器的 api 逻辑长时间运行,因此在任何响应被发回之前发送到服务器。
有人可以解释为什么这个 example 似乎超过了 ServicePointManager.DefaultConnectionLimit 的 2 吗?我最好的猜测是,由于我为每个请求创建一个新的HttpClient ServicePointManager 正在为每个请求创建一个ServicePoint 对象,但从我读到的内容来看,我认为ServicePointManager 应该只创建ServicePoint 的不同实例每个唯一的架构和域,所以我不确定。
注意:我确实计划重用我的 HttpClient 实例,但这个结果激发了我的好奇心 :)。
【问题讨论】:
标签: c# .net http tcp httpclient