【问题标题】:c# webclient not timing outc# webclient没有超时
【发布时间】:2017-09-13 16:34:25
【问题描述】:

我正在尝试使用设置了超时的扩展 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);
    }
}

【问题讨论】:

  • 您需要异步下载以保持 UI 处于活动状态
  • 该程序没有 UI,所以我不介意它是同步的。困扰我的是,如果网络出现问题,无法下载文件,那么下载不会超时。
  • 好的,看我的回答也许你可以实现异步调用并决定何时取消请求。如果没有取消下载,可能会使用时间并检查是否有下载进度

标签: c# timeout webclient


【解决方案1】:

试试这个,你可以避免 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;
    }

【讨论】:

    猜你喜欢
    • 2012-04-02
    • 2013-10-10
    • 2013-01-11
    • 1970-01-01
    • 2011-09-22
    • 2020-01-30
    • 2012-03-31
    • 2012-03-03
    • 2018-11-20
    相关资源
    最近更新 更多