web request timeout handling?

2019-04-09 12:38发布

问题:

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 ?

回答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:

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



回答2:

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.



回答3:

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