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

那些“好的”RFC 要求每个 RFC 客户端注意不要在每台主机上使用超过2个连接..。

微软在 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 属性对现有 对象; 它只影响 如果此属性的值未被初始化,则 直接或通过配置设置,该值默认为 常量默认持久连接限制”

我希望在实例化 WebClient 时配置这个限制,但是在程序开始时通过编程方式消除这个可悲的限制也可以。

我访问的服务器不是一个常规的网络服务器在互联网上,但在我的控制和本地局域网。我想做 API 调用,但我不使用网络服务或远程

50928 次浏览

If you find the ServicePoint object being used by your WebClient, you can change its connection limit. HttpWebRequest objects have an accessor to retrieve the one they were constructed to use, so you could do it that way. If you're lucky, all your requests might end up sharing the same ServicePoint so you'd only have to do it once.

I don't know of any global way to change the limit. If you altered the DefaultConnectionLimit early enough in execution, you'd probably be fine.

Alternately, you could just live with the connection limit, since most server software is going to throttle you anyway. :)

With some tips from here and elsewhere I managed to fix this in my application by overriding the WebClient class I was using:

class AwesomeWebClient : WebClient {
protected override WebRequest GetWebRequest(Uri address) {
HttpWebRequest req = (HttpWebRequest)base.GetWebRequest(address);
req.ServicePoint.ConnectionLimit = 10;
return (WebRequest)req;
}
}

We have a situation regarding the above piece of configuration in App.Config

In order for this to be valid in a CONSOLE Application, we added the System.Configuration reference dll. Without the reference, the above was useless.

for those interested:

System.Net.ServicePointManager.DefaultConnectionLimit = x (where x is your desired number of connections)

no need for extra references

just make sure this is called BEFORE the service point is created as mentioned above in the post.

This solution allows you to change the connection limit at any time:

private static void ConfigureServicePoint(Uri uri)
{
var servicePoint = ServicePointManager.FindServicePoint(uri);


// Increase the number of TCP connections from the default (2)
servicePoint.ConnectionLimit = 40;
}

The 1st time anyone calls this FindServicePoint, a ServicePoint instance is created and a WeakReference is created to hold on to it inside the ServicePointManager. Subsequent requests to the manager for the same Uri return the same instance. If the connection isn't used after, the GC cleans it up.