如何使用dotnet(nuget包)httpclient配置TCP连接数?

时间:2014-09-04 01:54:47

标签: c# asp.net-web-api httpwebrequest webclient dotnet-httpclient

我曾经使用HttpWebRequest.ServicePoint.ConnectionLimit(http://msdn.microsoft.com/en-us/library/system.net.servicepoint.connectionlimit(v=vs.110).aspx)来配置客户端打开的TCP连接数。

我计划将HttpCLient用于我的新应用程序。但是,我无法找到如何配置TCP连接数的相关信息。我认为它将通过 webrequesthandler http://msdn.microsoft.com/en-us/library/system.net.http.webrequesthandler.aspxAllowing Untrusted SSL Certificates with HttpClient中的一个属性公开,但我无法找到它。看起来它也不能通过自定义httpclient消息处理程序进行配置(http://www.asp.net/web-api/overview/advanced/httpclient-message-handlers

问题:

如何配置 TCP(持久)连接数?

更新1:

看起来它没有通过HttpClient公开(在通过ILSpy分析代码之后)。但是,看起来我可以使用ServicePointManager的FindServicePoint方法。任何人都可以确认这是否可行 - 找到我的uri的服务点并设置连接限制?

public static ServicePoint FindServicePoint(Uri address)
{
    return ServicePointManager.FindServicePoint(address, null);
}

更新2:

事实上,看起来这就是HttpWebRequest.ServicePoint在内部调用相同方法的方法。下面是来自ILSpy的相应代码片段 - 但是有很多servicepointmanager.findservicepoint(..)重载方法 - 选择正确的方法可能会很棘手。

Monitor.Enter(this, ref flag);
            if (this._ServicePoint == null || forceFind)
            {
                if (!this.ProxySet)
                {
                    this._Proxy = WebRequest.InternalDefaultWebProxy;
                }
                if (this._ProxyChain != null)
                {
                    this._ProxyChain.Dispose();
                }
                this._ServicePoint = ServicePointManager.FindServicePoint(this._Uri, this._Proxy, out this._ProxyChain, ref this._AbortDelegate, ref this.m_Aborted);
                if (Logging.On)
                {
                    Logging.Associate(Logging.Web, this, this._ServicePoint);
                }
            }

注意:我不想使用ServicePointManager。 DefaultConnectionLimit作为其全局。我正在寻找与 httpwebrequest.servicepoint.connectionlimit相关的内容,它是对每个服务点(主机)的请求和效果的本地

问候。

1 个答案:

答案 0 :(得分:0)

您可以使用SemphoreSlim来控制代码中创建请求的入口点,从而创建TCP端口。

How to limit the amount of concurrent async I/O operations?