c#webclient没有超时

时间:2017-04-18 01:09:09

标签: c# timeout webclient

我试图使用设置超时的扩展WebClient下载文件,我遇到超时问题(或者我认为应该导致超时)。

当我使用WebClient开始下载并接收一些数据时,请断开wifi - 我的程序在下载时挂起而不会抛出任何异常。我该如何解决这个问题? 编辑:它实际上抛出异常,但比它应该晚了(5分钟对比我设置的1秒) - 这就是我想要解决的问题。

如果您发现我的代码有任何其他问题,请告诉我。谢谢你的帮助

这是我的扩展课程

class WebClientWithTimeout : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest w = base.GetWebRequest(address);
        w.Timeout = 1000;
        return w;
    }
}

这是下载

using (WebClientWithTimeout wct = new WebClientWithTimeout())
{
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    try
    {
        wct.DownloadFile("https://example.com", file);
    }
    catch (Exception e)
    {
        Console.WriteLine("Download: {0} failed with exception:{1} {2}", file, Environment.NewLine, e);
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个,你可以避免UI阻塞。当设备连接到WiFi时,WiFi将继续下载。

//declare globally
 DateTime lastDownloaded = DateTime.Now;
 Timer t = new Timer();
 WebClient wc = new WebClient();

//声明你开始下载我的案例按钮点击

 private void button1_Click(object sender, EventArgs e)
    {

        wc.DownloadProgressChanged += Wc_DownloadProgressChanged;
        wc.DownloadFileCompleted += Wc_DownloadFileCompleted;
        lastDownloaded = DateTime.Now;
        t.Interval = 1000;
        t.Tick += T_Tick;
        wc.DownloadFileAsync(new Uri("https://github.com/google/google-api-dotnet-client/archive/master.zip"), @"C:\Users\chkri\AppData\Local\Temp\master.zip");
    }

    private void T_Tick(object sender, EventArgs e)
    {
        if ((DateTime.Now - lastDownloaded).TotalMilliseconds > 1000)
        {
            wc.CancelAsync();
        }
    }

    private void Wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            lblProgress.Text = e.Error.Message;
        }
    }

    private void Wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        lastDownloaded = DateTime.Now;
        lblProgress.Text = e.BytesReceived + "/" + e.TotalBytesToReceive;
    }