如何在WebClient.DownloadFileAsync中实现超时功能

3
所以我认为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(模拟Internet连接中断),我的应用程序只会暂停并停止下载,但它永远不会通过DownloadFileCompleted方法报告该问题。

因此,我希望在我的 WebClient.DownloadFileAsync 方法上实现一个超时。这可行吗?

另外,我正在使用 .Net 4,并且不想添加对第三方库的引用,因此无法使用 Async / Await 关键字。


这篇帖子提供了一种通用方法,我相信它可以更好地完成任务。 - Circle Hsiao
3个回答

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

否则,您可以创建自己的Web客户端。
  public class NewWebClient : WebClient
    {
        protected override WebRequest GetWebRequest(Uri address)
        {
            var req = base.GetWebRequest(address);
            req.Timeout = 18000;
            return req;
        }
    } 

1
非常糟糕的方法,需要额外的线程来计算时间,而这完全是不必要的。 - user586399
2
@Kilanny,你可以自由地回答更好的方法。这就是stackoverflow存在的意义。通过分享,你可以学到新的东西。 - Jerin
仅仅创建自己的Web客户端并不能与异步一起工作。你的第一个答案,使用CancelAsync是我知道的实现异步Web请求超时的唯一方法。谢谢。好答案。下面我会发布一个结合了这两个方法的答案。 - Evil August

1
创建一个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();
    }
}

这将允许您在下载文件时失去互联网连接时设置超时。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接