Parallel.For 发送多个 WebRequest

发布于 2024-12-05 12:48:20 字数 837 浏览 0 评论 0原文

我想发送多个 WebRequest。我使用 Parallel.For 循环来执行此操作,但循环运行一次,第二次在获取响应时给出错误。

错误:

操作超时

代码:

Parallel.For(0, 10, delegate(int i) {
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
        new Uri("http://www.mysite.com/service"));

    string dataToSend = "Data";
    byte[] buffer = System.Text.Encoding.GetEncoding(1252).
        GetBytes(dataToSend);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = buffer.Length;

    request.Host = "www.mysite.com";

    Stream requestStream = request.GetRequestStream();
    requestStream.Write(buffer, 0, buffer.Length);
    requestStream.Close();

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
});

I want to send multiple WebRequest. I used a Parallel.For loop to do that but the loop runs once and the second time it gives error while getting response.

Error:

The operation has timed out

Code :

Parallel.For(0, 10, delegate(int i) {
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
        new Uri("http://www.mysite.com/service"));

    string dataToSend = "Data";
    byte[] buffer = System.Text.Encoding.GetEncoding(1252).
        GetBytes(dataToSend);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = buffer.Length;

    request.Host = "www.mysite.com";

    Stream requestStream = request.GetRequestStream();
    requestStream.Write(buffer, 0, buffer.Length);
    requestStream.Close();

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
});

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

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

发布评论

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

评论(2

£冰雨忧蓝° 2024-12-12 12:48:20

最有可能的问题是,您需要在处理完响应后调用 response.Close()

Most likely the problem is that you need to call response.Close() after you're done processing the response.

香橙ぽ 2024-12-12 12:48:20

除了 Jim Mischel 所说的关于在响应上调用 Close 的内容之外,您还需要考虑到,默认情况下,.NET 将应用程序限制为每个域一次只能有两个活动 HTTP 连接。要更改此设置,您可以设置 System.Net.ServicePointManager.DefaultConnectionLimit以编程方式或使用 配置部分。

In addition to what Jim Mischel said about calling Close on the response, you also need to factor in that, by default, .NET limits an application to only two active HTTP connections per domain at once. To change this you can set System.Net.ServicePointManager.DefaultConnectionLimit programmatically or set the same thing via config using the <system.net><connectionManagement> configuration section.

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