Chr*_*ian 87 .net connection webclient http limit
那些"精细"的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>
Run Code Online (Sandbox Code Playgroud)
但是我怎么能以编程方式呢?
遵守 http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.defaultconnectionlimit.aspx
"更改DefaultConnectionLimit属性对现有ServicePoint对象没有影响;它仅影响在更改后初始化的ServicePoint对象.如果未直接或通过配置设置此属性的值,则该值默认为常量DefaultPersistentConnectionLimit."
我最好在我实现WebClient时配置限制,但只是在我的程序开始时以编程方式删除这个可怕的限制也没关系.
我访问的服务器不是互联网上的常规网络服务器,而是在我的控制下和本地局域网中.我想做API调用,但我不使用webservices或remoting
小智 119
感兴趣的人:
System.Net.ServicePointManager.DefaultConnectionLimit = x
(其中x是您所需的连接数)
无需额外的参考
只需确保在上面提到的帖子中创建服务点之前调用它.
Shi*_*zam 50
通过这里和其他地方的一些提示,我设法通过覆盖我正在使用的WebClient类来解决这个问题:
class AwesomeWebClient : WebClient {
protected override WebRequest GetWebRequest(Uri address) {
HttpWebRequest req = (HttpWebRequest)base.GetWebRequest(address);
req.ServicePoint.ConnectionLimit = 10;
return (WebRequest)req;
}
}
Run Code Online (Sandbox Code Playgroud)
该解决方案可让您在更改连接限制的任何时间:
private static void ConfigureServicePoint(Uri uri)
{
var servicePoint = ServicePointManager.FindServicePoint(uri);
// Increase the number of TCP connections from the default (2)
servicePoint.ConnectionLimit = 40;
}
Run Code Online (Sandbox Code Playgroud)
第一次有人调用此FindServicePoint时,会创建一个ServicePoint实例,并创建一个WeakReference以在ServicePointManager中保留它.对同一个Uri的管理器的后续请求返回相同的实例.如果之后没有使用连接,GC会将其清理干净.
如果您发现WebClient正在使用ServicePoint对象,则可以更改其连接限制.HttpWebRequest对象有一个访问器来检索它们构造使用的那个,所以你可以这样做.如果您很幸运,您的所有请求最终可能会共享同一个ServicePoint,因此您只需要执行一次.
我不知道有任何改变限制的全球方式.如果您在执行中足够早地更改了DefaultConnectionLimit,那么您可能没问题.
或者,你可以忍受连接限制,因为无论如何大多数服务器软件都会限制你.:)
归档时间: |
|
查看次数: |
46320 次 |
最近记录: |