我使用此脚本下载字符串
public class TimedWebClient: WebClient
{
public int Timeout { get; set; }
public TimedWebClient()
{
this.Timeout = 600000;
}
protected override WebRequest GetWebRequest(Uri address)
{
var objWebRequest= base.GetWebRequest(address);
objWebRequest.Timeout = this.Timeout;
return objWebRequest;
}
}
string s = new TimedWebClient {Timeout = 500}.DownloadString(URL);
但是如果它超时,我希望它显示一条消息。这可能吗?此脚本也会在加载时使表单无法访问,这非常烦人。
答案 0 :(得分:1)
如果请求超时,方法GetWebRequest()
将抛出异常。你只需要抓住被抛到那里的WebException
,例如通过写作
try {
string s = new TimedWebClient {Timeout = 500}.DownloadString(URL);
}
catch(WebException e) {
Console.WriteLine("Some kind of exception has appeared! (Timeout / Resource not available)");
}
还有关于你的
此脚本在加载时使表单无法访问,而且非常烦人
问题,您应该将下载任务平衡到另一个线程以避免这种情况,例如写
Task.Factory.StartNew(() => {
//Download the resource in this new thread, same code as above
});
请注意,这会使用TLP库,因此您需要
using System.Threading;
using System.Threading.Tasks;
在您的计划开始时。