【问题标题】:C# Does Each Instance of HttpClient Get it's Own ServicePointC# HttpClient 的每个实例是否都有自己的 ServicePoint
【发布时间】: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


    【解决方案1】:

    以防万一其他人好奇,我稍微检查了HttpClient 代码,看起来每个HttpClient 每个实例都实例化一个HttpMessageHandlerHttpMessageHandler 对象为每个实例创建一个哈希码,用于创建ServicePoint 对象,以及HttpClient 定义的 uri 的架构和域。

    【讨论】:

      【解决方案2】:

      @cjablonski76 我相信你的解释是错误的。因为ServicePoint的创建按照框架代码如下。

                  sp = new ServicePoint(address)
                  {
                      ConnectionLimit = DefaultConnectionLimit,
                      IdleSince = DateTime.Now,
                      Expect100Continue = Expect100Continue,
                      UseNagleAlgorithm = UseNagleAlgorithm
                  };
                  s_servicePointTable[tableKey] = new WeakReference<ServicePoint>(sp);
      

      如果你看到这个,说明没有使用支持你的陈述的哈希码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-20
        • 1970-01-01
        • 2021-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多