我正在尝试向第三方网站发送Web服务请求,该网站的服务器有点不可靠。有没有办法可以在对此站点的请求上设置超时?像这样的伪代码:
try // for 1 minute
{
// Make web request here
using (WebClient client new WebClient()) //...etc.
}
catch
{
}
答案 0 :(得分:23)
您可以使用Timeout属性:
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());
}
更新:
要回答有关XElement.Load(uri)
的评论部分中的问题,您可以执行以下操作:
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);
}
答案 1 :(得分:4)
WebClient自然不支持自定义超时。但是您可以使用自定义超时轻松构建派生类:
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;
}
}
答案 2 :(得分:2)
也许你应该选择
System.Net.WebRequest.Timeout
属性
答案 3 :(得分:1)
您可以从服务器端检查WebTimeout异常,然后使用SignalR主动将超时消息发送回客户端:
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!");
}
}
答案 4 :(得分:0)
.Net框架中涉及任何类型网络的许多类都包含Timeout属性。例如,WebRequest类(System.Net)上有这样的属性