简体   繁体   English

C#:当网页没有响应时,退出 System.Net.WebClient 下载(无论如何)

[英]C#: quit System.Net.WebClient download (of whatever) when webpage is not responding

If the website isn't responding after one second or so, it's probably safe to assume that it's a bad link and that I should move on to my next link in a set of "possible links."如果网站在一秒钟左右后没有响应,可以肯定地认为这是一个错误的链接,我应该在一组“可能的链接”中继续我的下一个链接。

How do I tell the WebClient to stop attempting to download after some predetermined amount of time?如何告诉WebClient在预定时间后停止尝试下载?

I suppose I could use a thread, but if it's taking longer than one second to download, that's ok.我想我可以使用线程,但如果下载时间超过一秒,那没关系。 I just want to make sure that it's connecting with the site.我只是想确保它与站点连接。

Perhaps I should modify the WebClient headers, but I don't see what I should modify.也许我应该修改WebClient标头,但我没有看到我应该修改什么。

Perhaps I should use some other class in the System.Net namespace?也许我应该在System.Net命名空间中使用其他一些 class ?

If you use the System.Net.WebRequest class you can set theTimeout property to be short and handle timeout exceptions.如果您使用System.Net.WebRequest class 您可以将Timeout属性设置为短并处理超时异常。

try{
    var request = WebRequest.Create("http://www.contoso.com");
    request.Timeout = 5000; //set the timeout to 5 seconds
    request.Method = "GET";
    var response = request.GetResponse();
}
catch(WebException webEx){
   //there was an error, likely a timeout, try another link here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM