Web请求超时处理? [英] web request timeout handling?
问题描述
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 20000;
using (WebResponse response = request.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
var result = reader.ReadToEnd();
// Do something with result
}
东西在上面的例子中,我有超时定义,如果碰巧击中超时我怎么会知道,结果将是空的?
In the above example I have a timeout defined, if it happens to hit the timeout how would I know, the result would be empty ?
我是否收到任何效应初探类型?
Do I receive any reponse types ?
我怎样才能确保我得到超时?
How can I make sure I got timed out ?
推荐答案
的GetResponse()
将抛出一个 引发WebException
。它的简单测试的究竟的会发生什么,但 - 超时设置为1毫秒,并尝试打什么这需要一段时间才能回来。
GetResponse()
would throw a WebException
. It's simple to test exactly what happens though - set the timeout to 1ms and try to hit anything which takes a while to come back.
在。事实上,文档状态此明确:
In fact, the documentation states this explicitly:
如果超时期满可以返回的资源面前,引发WebException。
If the timeout period expires before the resource can be returned, a WebException is thrown.
这篇关于Web请求超时处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!