Web请求超时处理? [英] web request timeout handling?

查看:176
本文介绍了Web请求超时处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 ?

我收到任何响应类型?

如何确定我已经超时?

推荐答案

GetResponse()将抛出一个 引发WebException 。很简单,只需要测试 尽管如此 - 将超时设置为1ms,并尝试点击任何需要一段时间的回来。

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.

事实上,文档明确表示: / p>

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆