简体   繁体   中英

c# webclient not timing out

Im trying to download files using extended WebClient with set timeout and I have a problem with the timeout (or what I think should cause timeout).

When I start the download with WebClient and receive some data, then disconnect wifi - my program hangs on the download without throwing any exception. How can I fix this?
EDIT: It actually throws exception but way later than it should (5 minutes vs 1 second which i set) - that is what Im trying to fix.

If you find anything else wrong with my code, please let me know too. Thank you for help

This is my extended class

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

This is the download

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

Try this, you can avoid UI blocking by this. Coming the WiFi when device connects to WiFi the download resumes.

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

//declarewherever you initiate download my case button click

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM