簡體   English   中英

C#WebClient不超時

[英]c# webclient not timing out

我試圖使用設置了超時的擴展WebClient下載文件,但是超時(或我認為應該引起超時的問題)有問題。

當我使用WebClient開始下載並接收一些數據時,然后斷開wifi的連接-我的程序掛起了下載,沒有引發任何異常。 我怎樣才能解決這個問題?
編輯:它實際上引發異常,但是比它應該晚(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);
    }
}

試試這個,您可以避免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;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM