0

I made a simple download manager based on WebClient. somthing like this:

    public class DownloadManager(){

     public static Dictionary<string,WebClient> DownloadList{get;set;}
         //...
         
     public static WebClient CheckInProgressDownload(string key)
        {
            System.Net.WebClient result;

            if (DownloadsList.TryGetValue(key, out result))
            {
               
                return result;
            }
            else
            {
                return null;
            }
        }
       
    }

By getting specific WebClient Object from DownloadList property I can show download progress in a dynamically created Progress Bar. When I Create a new instance of progress bar I have to subscribe to WebClient DownloadFileCompleted and DownloadProgressChanged events.

 public calss ProgressConrolGroup(){
    
    public void OnCreate(){
    
       var wc = new DownloadManager.CheckInProgressDownload(stringkey);
       
      if(wc!=null){
              wc.DownloadProgressChanged += WC_DownloadProgressChanged;
       }
    
    }

private void WC_DownloadProgressChanged(object sender,System.Net.DownloadProgressChangedEventArgs e) 
    {
    progressbar.Progress = e.ProgressPercentage;
     }
}

My Problem is as you see , every time I get Existing WebClient Object from list, It has Previously Event handler attached to it. how can I remove its event handlers and add new one?

important note: I saw some answer on stack overflow but none of them were useful to me. like this Get compiler generated delegate for an event and this one remove all EventHandlers of a specific Control. and this example either :How to remove all event handlers from an event .

  • Before `wc.DownloadProgressChanged += WC_DownloadProgressChanged;` add `wc.DownloadProgressChanged -= WC_DownloadProgressChanged;` ? – dr.null Nov 19 '20 at 22:42
  • @dr.null I tried this too. even did it in a loop and remove handler multiple times. didn't work. – Icosahedron Nov 19 '20 at 23:01
  • 1
    Excuse me. Are you using a single `ProgressBar` here? If that so, the `WC_DownloadProgressChanged` event will fire for each subscribed instance and update the progress with its own percentage. Either, sum the total download size and show the overall progress, or better use an `async` pattern to download a file from the queue and show its progress. Something like [this](https://stackoverflow.com/a/39553778/14171304). – dr.null Nov 19 '20 at 23:34

0 Answers0