c# - 如何在 WebClient.DownloadFileAsync 上实现超时

标签 c# .net-4.0 timeout webclient

所以我认为 Webclient.DownloadFileAysnc 会有一个默认超时,但是查看文档我无法在任何地方找到任何关于它的信息,所以我猜它没有。

我正在尝试像这样从 Internet 下载文件:

 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 方法报告。

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

顺便说一句,我使用的是 .Net 4,不想添加对第三方库的引用,所以不能使用 Async/Await 关键字

最佳答案

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

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

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

关于c# - 如何在 WebClient.DownloadFileAsync 上实现超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30618452/

相关文章:

c# - 使用对象初始化器有什么好处吗?

bash - 使用超时命令时出错 - 无效的时间间隔

python - 使用twisted的爬虫,getPage出现超时错误怎么办?

c# - Windows 服务加 GUI/C#

c# - OleDbAdapter 读取列数据

c# - 如何自动将 .Net 3.5 升级到 .Net 4.0,包括引用资料?

c# - IEnumerable 不在 foreach 中枚举

c# - 具有两个数据库的单个类

.net - 由于 2 秒超时,并非所有 native 全局变量都在混合模式 .Net 应用程序中被破坏

c# - MS SQL 数据库作为 C#、MVC Entity Framework 应用程序的服务连接字符串