Web request timeout in .NET

.net, asp.net-mvc, c#, web-services

Solution

You could use the Timeout property:

var request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
request.Timeout = 1000; //Timeout after 1000 ms
using (var stream = request.GetResponse().GetResponseStream())
using (var reader = new StreamReader(stream))
{
    Console.WriteLine(reader.ReadToEnd());
}

UPDATE:

To answer the question in the comment section about `XElement.Load(uri)` you could do the following:

var request = (HttpWebRequest)WebRequest.Create("http://stackoverflow.com/feeds");
request.Timeout = 1000; //Timeout after 1000 ms
using (var stream = request.GetResponse().GetResponseStream())
using (var reader = new StreamReader(stream))
{
    var xel = XElement.Load(reader);
}

Problem

I am trying to make a web service request call to a third part web site who's server is a little unreliable. Is there a way I can set a timeout on a request to this site? Something like this pseudo code: ``` try // for 1 minute { // Make web request here using (WebClient client new WebClient()) //...etc. } catch { } ```

Original source