Passing a method to a backgroundworker dowork

前端 未结 3 1938
感动是毒
感动是毒 2021-01-14 11:50

In the code below, is there a way to instead of always subscribing the updateWorker_DoWork method, pass it a method like this

public void GetUpdates(SomeObje         


        
3条回答
  •  执念已碎
    2021-01-14 12:07

    Worked it out, was way simpler than I was thinking. Just had to make a delegate for the method called on DoWork. Probably should have phrased my original question better.

        public delegate void DoWorkDelegate(object sender,DoWorkEventArgs e);
    
         public void GetUpdates()
         {
             StartWorker(new DoWorkDelegate(updateWorker_DoWork));
         }
    
         public void StartWorker(DoWorkDelegate task)
         {
             //Set up worker
             updateWorker.WorkerReportsProgress = true;
             updateWorker.WorkerSupportsCancellation = true;
             updateWorker.DoWork += new DoWorkEventHandler(task);
             updateWorker.RunWorkerCompleted +=
                 new RunWorkerCompletedEventHandler(updateWorker_RunWorkerCompleted);
             updateWorker.ProgressChanged +=
                 new ProgressChangedEventHandler(updateWorker_ProgressChanged);
    
             //Run worker
             _canCancelWorker = true;
             updateWorker.RunWorkerAsync();
             //Initial Progress zero percent event
             _thes.UpdateProgress(0);
         }
    
          private void updateWorker_DoWork(object sender, DoWorkEventArgs e)
          {
              BackgroundWorker worker = sender as BackgroundWorker;
              e.Result = GetUpdatesTask(worker, e);
          }
    

提交回复
热议问题