简体   繁体   English

C#WebClient不超时

[英]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). 我试图使用设置了超时的扩展WebClient下载文件,但是超时(或我认为应该引起超时的问题)有问题。

When I start the download with WebClient and receive some data, then disconnect wifi - my program hangs on the download without throwing any exception. 当我使用WebClient开始下载并接收一些数据时,然后断开wifi的连接-我的程序挂起了下载,没有引发任何异常。 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. 编辑:它实际上引发异常,但是比它应该晚(5分钟vs我设置的1秒)-这就是我试图修复的问题。

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. 试试这个,您可以避免UI阻塞。 Coming the WiFi when device connects to WiFi the download resumes. 当设备连接到WiFi时进入WiFi,下载将恢复。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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