ServicePoint 安全检查以防止阻塞新的 HttpWebRequest

发布于 2024-12-17 01:36:18 字数 595 浏览 1 评论 0原文

我正在使用第 3 方库来进行多次 http 调用。通过反编译代码,我确定它正在创建并使用原始的 HttpWebRequest,所有内容都指向一个 URL。问题是某些请求没有正确关闭。一段时间后,当库对它们调用 GetRequestStream()* 时,所有新的 HttpWebRequest 都会永远阻塞。我已确定此阻塞是由于该特定主机的 ServicePoint 上的 ConnectionLimit 造成的,其默认值为 2。换句话说,该库已打开 2 个请求,然后尝试打开第 3 个请求,该请求被阻塞。

我想防止这种阻塞。该库具有相当的弹性,并且会自行重新连接,因此如果我终止它已建立的现有连接也没关系。问题是我无权访问该库生成的任何 HttpWebRequest 或 HttpWebResponse 。不过我确实知道它访问的 URL,因此我可以访问它的 ServicePoint

var sp = ServicePointManager.FindServicePoint(new Uri("http://UrlThatIKnowAbout.com"));

(注意:这些 HttpWebRequest 上启用了 KeepAlive)

I'm using a 3rd party library that makes a number of http calls. By decompiling the code, I've determined that it is creating and using raw HttpWebRequest's, all going to a single URL. The issue is that some of the requests don't get closed properly. After some time, all new HttpWebRequest's block forever when the library calls GetRequestStream()* on them. I've determined this blocking is due to the ConnectionLimit on the ServicePoint for that particular host, which has the default value of 2. In other words, the library has opened 2 requests, and then tries to open a 3rd, which blocks.

I want to protect against this blocking. The library is fairly resilient and will reconnect itself, so it's okay if I kill the existing connections it has made. The problem is that I don't have access to any of the HttpWebRequest or HttpWebResponses this library makes. However I do know the URL it accesses and therefore I can access the ServicePoint for it.

var sp = ServicePointManager.FindServicePoint(new Uri("http://UrlThatIKnowAbout.com"));

(Note: KeepAlive is enabled on these HttpWebRequests)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

叹梦 2024-12-24 01:36:18

这很有效,尽管我不确定这是解决问题的最佳方法。

  1. 获取url的服务点对象
    var sp = ServicePointManager.FindServicePoint(new Uri("http://UrlThatIKnowAbout.com"));
  2. ConnectionLimit 增加到 int.MaxValue
  3. 创建一个后台线程,定期检查服务点上的ConnectionCount。如果超过 5,请调用 CloseConnectionGroup()
  4. MaxIdleTime 设置为 1 小时(而不是默认值)

设置 ConnectionLimit 应防止阻塞。监视器线程将确保太多连接永远不会同时处于活动状态。设置 MaxIdleTime 应该作为后备措施。

This worked, though I'm not sure it's the best way to solve the problem.

  1. Get the service point object for the url
    var sp = ServicePointManager.FindServicePoint(new Uri("http://UrlThatIKnowAbout.com"));
  2. Increase the ConnectionLimit to int.MaxValue
  3. Create a background thread that periodically checks the ConnectionCount on the service point. If it goes above 5, call CloseConnectionGroup()
  4. Set MaxIdleTime to 1 hour (instead of default)

Setting the ConnectionLimit should prevent the blocking. The monitor thread will ensure that too many connections are never active at the same time. Setting MaxIdleTime should serve as a fall back.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文