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 ?
Timeouts can be easily added to the URL you are requesting. It so happens that, you are using a third-party URL and waiting for a response. It is always a good practice to give a timeout on the URL, as we might want the URL to respond within a timespan with a response or an error.
If you really need to implement a timeout on the API side itself, I would recommend creating a thread to do your work in, and then cancelling it after a certain period. You could for example put it in a Task , create your 'timeout' task using Task. Wait and use Task. WaitAny for the first one to come back.
The HyperText Transfer Protocol (HTTP) 408 Request Timeout response status code means that the server would like to shut down this unused connection. It is sent on an idle connection by some servers, even without any previous request by the client.
The default value is 100,000 milliseconds (100 seconds).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With