我想终止一个httpwebrequest,当它需要太长时间的连接。下面是我写的一段简单的代码:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Timeout = 5000;
request.ReadWriteTimeout = 5000;
request.Proxy = new WebProxy("http://" + proxyUsed + "/", true);
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.01; Windows NT 5.0)";
using (WebResponse myResponse = request.GetResponse())
{
using (Stream s = myResponse.GetResponseStream())
{
s.ReadTimeout = 5000;
s.WriteTimeout = 5000;
using (StreamReader sr = new StreamReader(s, System.Text.Encoding.UTF8))
{
result = sr.ReadToEnd();
httpLink = myResponse.ResponseUri.AbsoluteUri;
sr.Close();
}
s.Close();
}
myResponse.Close();
}
然而,有时连接需要大约15分钟才能获得响应。情况是15分钟后,我仍然可以得到响应,但不是URL的完整源代码。我猜连接太慢了,URL在超时时间内响应我一点数据,只是说例如在5秒内接收1字节,所以它不会过期,但它很长。如何终止连接?谢谢:)
您可能会发现超时实际上是有效的,但是线程在试图关闭流时挂起。我不知道为什么会这样,但有时候就是这样。我从未使用过ReadToEnd
,但我在使用Read
时遇到过这种情况。
在我关闭流之前,我通过在请求上调用Abort
来修复这个问题。它有点笨重,但很有效。下面的简短代码展示了该技术。
HttpWebResponse response = null;
StreamReader sr = null;
try
{
response = (HttpWebResponse)request.GetResponse(...);
Stream s = response.GetResponseStream();
sr = new StreamReader(s, Encoding.UTF8);
// do your reading here
}
finally
{
request.Abort(); // !! Yes, abort the request
if (sr != null)
sr.Dispose();
if (response != null)
response.Close();
}
我发现ReadTimeout
和ReadWriteTimeout
工作如预期。也就是说,当读取超时时,执行确实转到finally
块。如果request.Abort
不在那里,对sr.Dispose
的调用将挂起。
中断流读取,如果总时间太长则中止。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Timeout = 5000;
request.ReadWriteTimeout = 5000;
request.Proxy = new WebProxy("http://" + proxyUsed + "/", true);
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.01; Windows NT 5.0)";//ahem! :)
DateTime giveUp = DateTime.UtcNow.AddSeconds(5);
using (WebResponse myResponse = request.GetResponse())
{
httpLink = myResponse.ResponseUri.AbsoluteUri;
using (Stream s = myResponse.GetResponseStream())
{
s.ReadTimeout = 5000;
s.WriteTimeout = 5000;
char[] buffer = new char[4096];
StringBuilder sb = new StringBuilder()
using (StreamReader sr = new StreamReader(s, System.Text.Encoding.UTF8))
{
for(int read = sr.Read(buffer, 0, 4096); read != 0; read = sr.Read(buffer, 0, 4096))
{
if(DateTime.UtcNow > giveUp)
throw new TimeoutException();
sb.Append(buffer, 0, read);
}
result = sb.ToString();
}
}
}
确保在异常情况下也关闭连接。在这种情况下,WebResponse对象位于WebException:
try
{
using (WebResponse myResponse = request.GetResponse())
// do stuff
}
catch (WebException webEx)
{
webEx.Response.Close();
}