WebClient.DownloadProgressChanged never gets called

后端 未结 2 483
我寻月下人不归
我寻月下人不归 2021-01-02 14:10

I added an event handler to the WebClient\'s DownloadProgressChanged event, but it never seems to fire. The file successfully downloads, but without having its

相关标签:
2条回答
  • 2021-01-02 14:32
    client.DownloadFile(url, savepath);
    

    You have to use the async version to download a file, currently you use the blocking, synchronous version.

    From the msdn docs for WebClient.DownloadProgressChanged:

    Occurs when an asynchronous download operation successfully transfers some or all of the data.

    In your case that would be:

    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
    client.DownloadFileAsync (url, savepath);
    

    Since your method does not directly return any result, this refactoring shouldn't be a problem, note though that the download most likely has not been completed by the time the method returns to the caller.

    0 讨论(0)
  • 2021-01-02 14:51

    If you want to use WebClient synchronously, while getting progress updates you can rely on this method detailed here

    http://alexfeinberg.wordpress.com/2014/09/14/how-to-use-net-webclient-synchronously-and-still-receive-progress-updates/

    public void DownloadFile(Uri uri, string desintaion)
    {
      using(var wc = new WebClient())
      {
        wc.DownloadProgressChanged += HandleDownloadProgress;
        wc.DownloadFileCompleted += HandleDownloadComplete;
    
        var syncObject = new Object();
        lock(syncObject)
        {
           wc.DownloadFileAsync(sourceUri, destination, syncObject);
           //This would block the thread until download completes
           Monitor.Wait(syncObject);
        }
      }
    
      //Do more stuff after download was complete
    }
    
    public void HandleDownloadComplete(object sender, AsyncCompletedEventArgs args)
    {
       lock(e.UserState)
       {  
          //releases blocked thread
          Monitor.Pulse(e.UserState);
       }
    }
    
    
    public void HandleDownloadProgress(object sender, DownloadProgressChangedEventArgs args)
    {
      //Process progress updates here
    }
    
    0 讨论(0)
提交回复
热议问题