我有一个继承WebClient的类:
public class WebDownload : WebClient
{
/// <summary>
/// Time in milliseconds
/// </summary>
public int Timeout { get; set; }
public WebDownload() : this(10000) { }
public WebDownload(int timeout)
{
this.Timeout = timeout;
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request != null)
{
request.Timeout = this.Timeout;
}
return request;
}
}在我的代码中,我循环了大量的Urls,然后用以下方法一个接一个地下载:
string source;
using (WebDownload client = new WebDownload()) // WebClient class inherits IDisposable
{
client.Headers.Add("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:26.0) Gecko/20100101 Firefox/26.0");
source = client.DownloadString(url);
}
return source;我遇到的一个问题是,有时代码会卡在这个方法上:
source = client.DownloadString(url);知道为什么会这样吗?如果请求失败,我使用10秒的Timeout来停止请求。
发布于 2014-02-26 23:32:14
如果您的DownloadString被卡住了,请尝试使用DownloadStringAsync。长时间运行的操作应该异步运行。
WebClient w = new WebClient();
w.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(downloadCompleted);
w.DownloadStringAsync(new Uri("http://stackoverflow.com"));在本例中,自定义方法downloadCompleted在下载完成后发生,您将在Result属性中获得下载的字符串。
如果需要,可以使用CancelAsync取消异步操作。
https://stackoverflow.com/questions/21230779
复制相似问题