Parallel.For 发送多个 WebRequest
我想发送多个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最有可能的问题是,您需要在处理完响应后调用
response.Close()
。Most likely the problem is that you need to call
response.Close()
after you're done processing the response.除了 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.