如何在WebClient.DownloadFileAsync上实现超时 [英] How to implement a Timeout on WebClient.DownloadFileAsync

查看:342
本文介绍了如何在WebClient.DownloadFileAsync上实现超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我认为 Webclient.DownloadFileAysnc 会具有默认超时,但是环顾文档,我在任何地方都找不到它,所以我猜没有。

So I thought Webclient.DownloadFileAysnc would have a default timeout but looking around the documentation I cannot find anything about it anywhere so I'm guessing it doesn't.

我正尝试从互联网下载文件,如下所示:

I am trying to download a file from the internet like so:

 using (WebClient wc = new WebClient())
 {
      wc.DownloadProgressChanged += ((sender, args) =>
      {
            IndividualProgress = args.ProgressPercentage;
       });
       wc.DownloadFileCompleted += ((sender, args) =>
       {
             if (args.Error == null)
             {
                  if (!args.Cancelled)
                  {
                       File.Move(filePath, Path.ChangeExtension(filePath, ".jpg"));
                  }
                  mr.Set();
              }
              else
              {
                    ex = args.Error;
                    mr.Set();
              }
        });
        wc.DownloadFileAsync(new Uri("MyInternetFile", filePath);
        mr.WaitOne();
        if (ex != null)
        {
             throw ex;
        }
  }

但是,如果我关闭WiFi(模拟互联网连接断开)我的应用程序只是暂停并且下载停止,但是它永远不会通过 DownloadFileCompleted 方法报告该情况。

But if I turn off my WiFi (simulating a drop of internet connection) my application just pauses and the download stops but it will never report that through to the DownloadFileCompleted method.

由于这个原因,我想在 WebClient.DownloadFileAsync 方法上实现超时。这可能吗?

For this reason I would like to implement a timeout on my WebClient.DownloadFileAsync method. Is this possible?

顺便说一句,我正在使用.Net 4,并且不想添加对第三方库的引用,因此不能使用 Async / Await 关键字

As an aside I am using .Net 4 and don't want to add references to third party libraries so cannot use the Async/Await keywords

推荐答案

您可以使用WebClient.DownloadFileAsync()。现在在计时器内,您可以像这样调用CancelAsync():

You can use WebClient.DownloadFileAsync(). Now inside a timer you can call CancelAsync() like so:

System.Timers.Timer aTimer = new System.Timers.Timer();
System.Timers.ElapsedEventHandler handler = null;
handler = ((sender, args)
      =>
     {
         aTimer.Elapsed -= handler;
         wc.CancelAsync();
      });
aTimer.Elapsed += handler;
aTimer.Interval = 100000;
aTimer.Enabled = true;

否则创建您自己的weclient

Else create your own weclient

  public class NewWebClient : WebClient
    {
        protected override WebRequest GetWebRequest(Uri address)
        {
            var req = base.GetWebRequest(address);
            req.Timeout = 18000;
            return req;
        }
    } 

这篇关于如何在WebClient.DownloadFileAsync上实现超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆