在Parallel.For中发送多个WebRequest

Ank*_*kit 10 c# httpwebrequest task-parallel-library

我想发送多个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();
});
Run Code Online (Sandbox Code Playgroud)

Dre*_*rsh 12

除了Jim Mischel关于在响应中调用Close的内容之外,您还需要考虑到默认情况下,.NET会将应用程序限制为每个域只有两个活动HTTP连接.要更改此设置,您可以System.Net.ServicePointManager.DefaultConnectionLimit使用<system.net><connectionManagement>配置部分以编程方式设置或通过配置设置相同的内容.


Jim*_*hel 10

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