代码之家  ›  专栏  ›  技术社区  ›  Christian

如何以编程方式删除WebClient中的2连接限制

  •  86
  • Christian  · 技术社区  · 17 年前

    那些“优秀”的RFC要求每个RFC客户端注意每个主机不使用超过2个连接。。。

    Microsoft在WebClient中实现了这一点。我知道它可以关闭与

    App.config:

    <?xml version="1.0" encoding="utf-8" ?> 
    <configuration> 
     <system.net> 
      <connectionManagement> 
       <add address="*" maxconnection="100" /> 
      </connectionManagement> 
     </system.net> 
    </configuration> 
    

    (于 http://social.msdn.microsoft.com/forums/en-US/netfxnetcom/thread/1f863f20-09f9-49a5-8eee-17a89b591007 )

    但是我如何以编程的方式来做呢?

    依照 http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.defaultconnectionlimit.aspx

    “更改DefaultConnectionLimit属性对现有连接没有影响 更改后初始化。如果此属性的值尚未更改 直接设置或通过配置设置,该值默认为 常量DefaultPersistentConnectionLimit。“

    我最希望在实例化WebClient时配置该限制,但在程序开始时以编程方式删除该限制也可以。

    我访问的服务器不是internet上的常规Web服务器,而是在我的控制下和本地lan中。我想进行API调用,但我不使用Web服务或远程处理

    5 回复  |  直到 17 年前
        1
  •  120
  •   John Saunders    16 年前

    有兴趣的人士:

    System.Net.ServicePointManager.DefaultConnectionLimit = x (其中x是所需的连接数)

    不需要额外的参考资料

    只需确保在创建服务点之前调用它,如上文所述。

        2
  •  50
  •   Shizam    17 年前

    通过这里和其他地方的一些提示,我通过覆盖我使用的WebClient类,在我的应用程序中解决了这个问题:

    class AwesomeWebClient : WebClient {
        protected override WebRequest GetWebRequest(Uri address) {
            HttpWebRequest req = (HttpWebRequest)base.GetWebRequest(address);
            req.ServicePoint.ConnectionLimit = 10;
            return (WebRequest)req;
        }
    }
    
        3
  •  7
  •   George Tsiokos    11 年前

    此解决方案允许您在以下位置更改连接限制: 随时 :

    private static void ConfigureServicePoint(Uri uri)
    {
        var servicePoint = ServicePointManager.FindServicePoint(uri);
    
        // Increase the number of TCP connections from the default (2)
        servicePoint.ConnectionLimit = 40;
    }
    

    第一次有人这么叫 FindServicePoint A. ServicePoint 实例,并创建一个 WeakReference 创建以在 ServicePointManager . 对管理器的相同Uri的后续请求返回相同的实例。如果在之后未使用连接,则GC会将其清除。

        4
  •  5
  •   Katelyn Gadd    17 年前

    如果发现WebClient正在使用ServicePoint对象,则可以更改其连接限制。HttpWebRequest对象有一个访问器来检索它们构造使用的访问器,因此您可以这样做。如果幸运的话,您的所有请求可能最终共享同一个ServicePoint,因此您只需执行一次。

    我不知道有什么全球性的办法来改变限额。如果您在执行时足够早地更改了DefaultConnectionLimit,您可能会很好。

    或者,您也可以接受连接限制,因为大多数服务器软件都会限制您的连接

        5
  •  4
  •   Teo-Kostas    16 年前

    我们在App.Config中遇到了与上述配置相关的情况

    我们添加了System.Configuration参考dll。 没有参考资料,上述内容毫无用处。