WebClient DownloadString卡住了

时间:2014-01-20 09:51:21

标签: c# .net

我有这个类继承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停止请求。

1 个答案:

答案 0 :(得分:1)

如果您的DownloadString卡住,请尝试使用DownloadStringAsync。 长时间运行的操作应该异步运行。

WebClient w = new WebClient();
w.DownloadStringCompleted += 
                   new DownloadStringCompletedEventHandler(downloadCompleted);
w.DownloadStringAsync(new Uri("http://stackoverflow.com"));

在此示例中,自定义方法 downloadCompleted 在下载完成后发生,您将在Result属性中提供下载的字符串。

如果需要,您可以使用CancelAsync取消异步操作。

相关问题