2017-04-18 99 views
0

我试图下载文件使用扩展WebClient与设置超时,我有超时(或我认为应该导致超时)的问题。c#webclient不超时

当我开始下载WebClient并接收一些数据,然后断开无线 - 我的程序挂在下载没有任何异常。我怎样才能解决这个问题?
编辑:它实际上抛出异常,但方式晚于它应该(5分钟vs 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); 
    } 
} 
+0

您需要异步下载,以保持UI活跃 – Krishna

+0

可是没有UI程序,所以我真的不介意它是同步的。令我困扰的是,如果网络上发生了一些事情,并且文件无法下载,那么下载并没有超时。 – nubi

+0

没关系,看到我的答案也许你可以实现异步调用,并决定何时取消请求。也许使用一段时间,并检查是否有下载进度,如果不取消下载 – Krishna

回答

0

试试这个,你能避免这个UI阻塞。当设备连接到WiFi时,下载将恢复。

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

// declarewherever你开始下载我的情况下点击链接

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