如何在WebClient.DownloadFileAsync上实现超时

时间:2015-06-03 11:11:43

标签: c# .net-4.0 timeout webclient

所以我认为Webclient.DownloadFileAysnc会有默认超时但是查看文档时我无法在任何地方找到任何内容,所以我猜不出来。

我正试图从互联网上下载文件:

 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关键字

3 个答案:

答案 0 :(得分:3)

您可以使用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;
        }
    } 

答案 1 :(得分:0)

创建一个WebClientAsync类,在构造函数中实现计时器。这样您就不会将计时器代码复制并粘贴到每个实现中。

public class WebClientAsync : WebClient
{
    private int _timeoutMilliseconds;

    public EdmapWebClientAsync(int timeoutSeconds)
    {
        _timeoutMilliseconds = timeoutSeconds * 1000;

        Timer timer = new Timer(_timeoutMilliseconds);
        ElapsedEventHandler handler = null;

        handler = ((sender, args) =>
        {
            timer.Elapsed -= handler;
            this.CancelAsync();
        });

        timer.Elapsed += handler;
        timer.Enabled = true;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        request.Timeout = _timeoutMilliseconds;
        ((HttpWebRequest)request).ReadWriteTimeout = _timeoutMilliseconds;

        return request;
    }



    protected override voidOnDownloadProgressChanged(DownloadProgressChangedEventArgs e)
    {
        base.OnDownloadProgressChanged(e);
        timer.Reset(); //If this does not work try below
        timer.Start();
    }
}

如果在下载文件时丢失了Internet连接,这将允许您超时。

答案 2 :(得分:0)

这是另一种实现方式,我试图避免使用任何共享的类/对象变量,以免多次调用带来麻烦:

 public Task<string> DownloadFile(Uri url)
        {
            var tcs = new TaskCompletionSource<string>();
            Task.Run(async () =>
            {
                bool hasProgresChanged = false;
                var timer = new Timer(new TimeSpan(0, 0, 20).TotalMilliseconds);
                var client = new WebClient();

                void downloadHandler(object s, DownloadProgressChangedEventArgs e) => hasProgresChanged = true;
                void timerHandler(object s, ElapsedEventArgs e)
                {
                    timer.Stop();
                    if (hasProgresChanged)
                    {
                        timer.Start();
                        hasProgresChanged = false;
                    }
                    else
                    {
                        CleanResources();
                        tcs.TrySetException(new TimeoutException("Download timedout"));
                    }
                }
                void CleanResources()
                {
                    client.DownloadProgressChanged -= downloadHandler;
                    client.Dispose();
                    timer.Elapsed -= timerHandler;
                    timer.Dispose();
                }

                string filePath = Path.Combine(Path.GetTempPath(), Path.GetFileName(url.ToString()));
                try
                {
                    client.DownloadProgressChanged += downloadHandler;
                    timer.Elapsed += timerHandler;
                    timer.Start();
                    await client.DownloadFileTaskAsync(url, filePath);
                }
                catch (Exception e)
                {
                    tcs.TrySetException(e);
                }
                finally
                {
                    CleanResources();
                }

                return tcs.TrySetResult(filePath);
            });

            return tcs.Task;
        }