web request timeout handling?

2019-04-09 12:03发布

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 ?

3条回答
等我变得足够好
2楼-- · 2019-04-09 12:30

You should probably be using HTTPWebResponse. It has a status code that tells you that information and more. HTTPWebResponse is a descendant of WebResponse.

查看更多
Luminary・发光体
3楼-- · 2019-04-09 12:46

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:

If the timeout period expires before the resource can be returned, a WebException is thrown.

查看更多
在下西门庆
4楼-- · 2019-04-09 12:52

Your HttpWebRequest.GetResponse call will throw a WebException when;

Abort was previously called.    
-or-    
The time-out period for the request expired.
-or-    
An error occurred while processing the request.

Catch this exception.

I used to just pull my network cable out to test this sort of thing although you could be more elegant and use a proxy tool and block that particular request.

查看更多
登录 后发表回答