简体   繁体   中英

How to implement a Timeout on WebClient.DownloadFileAsync

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

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.

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

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

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;

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

Create a WebClientAsync class that implements the timer in the constructor. This way you aren't copying and pasting the timer code into every implementation.

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

This will allow you to timeout if you lose Internet connection while downloading a file.

Here is another implementation, I tried to avoid any shared class/object variables to avoid trouble with multiple calls:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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