Search code examples
c#error-handlingtimeoutwebrequest

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 ?


Solution

  • 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.