2017-04-18 101 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; 
    }