2015-09-04 47 views
0

我使用这个脚本下载一个字符串超时下载字符串消息

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); 

但我想让它显示一个消息,如果超时。这可能吗?此外,这个脚本使得表单在加载时无法访问,这非常烦人。

回答

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)"); 
} 

而且涉及您的

这个脚本使表单unaccesable同时加载和多数民众柠恼人

的问题,您应该平衡下载任务到另一个线程来避免,例如写

Task.Factory.StartNew(() => { 
     //Download the resource in this new thread, same code as above 
}); 

请注意,这里使用了TLP库,所以你需要一个

using System.Threading; 
using System.Threading.Tasks; 

在你的程序的开始。

+0

你是一个传奇人物,这是我有过堆栈溢出的最佳答案,我希望我能代表你,但我不能因为我的新! –

+0

谢谢这么多:D! –