Web request timeout in .NET
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?开发者_JS百科 Something like this pseudo code:
try // for 1 minute
{
// Make web request here
using (WebClient client new WebClient()) //...etc.
}
catch
{
}
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);
}
WebClient does not naturally support custom timeouts. But you can easily build a derived class with custom timeouts:
public class TimeoutWebClient : WebClient
{
private int _timeOut = 10000;
public int TimeOut
{
get
{
return _timeOut;
}
set
{
_timeOut = value;
}
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest webRequest = base.GetWebRequest(address);
webRequest.Timeout = _timeOut;
return webRequest;
}
}
Source: http://aspadvice.com/blogs/maniknet/archive/2008/06/16/Ganz-kurz_3A00_-WebClient-mit-eigenem-Verbindungs-Timeout-_2800_WebClient-with-a-custom-connection-timeout_2900_.aspx
Maybe you should go with
System.Net.WebRequest.Timeout
propertyYou could check for WebTimeout exception from server side then use SignalR to actively send timeout messsage back to clients:
var request = (HttpWebRequest)WebRequest.Create("http://www.your_third_parties_page.com");
request.Timeout = 1000; //Timeout after 1000 ms
try
{
using (var stream = request.GetResponse().GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.Timeout)
{
//If timeout then send SignalR message to inform the clients...
var context = GlobalHost.ConnectionManager.GetHubContext<YourHub>();
context.Clients.All.addNewMessageToPage("This behavious have been processing too long!");
}
}
See more how to setup SignalR for asp.net here
Many classes within .Net framework that involve any kind of networking include a Timeout property. For instance, there's such a property on the WebRequest class (System.Net)
精彩评论