Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to use System.ComponentModel.BackgroundWorker with lambda in C#

I want to know the best way to do that:

using (var backgroundWorker = new BackgroundWorker())
{
    DoWorkEventHandler doWorkHandler = null;
    doWorkHandler = (s, e) =>
        {
            //Some expensive code goes here...
            backgroundWorker.DoWork -= doWorkHandler;
            //or
            //((BackgroundWorker)s).DoWork -= doWorkHandler;
        };
    backgroundWorker.DoWork += doWorkHandler;

    RunWorkerCompletedEventHandler workerCompleted = null;
    workerCompleted = (s, e) =>
        {
            //Update IU or something...
            backgroundWorker.RunWorkerCompleted -= workerCompleted;
            //or
            //((BackgroundWorker)s).RunWorkerCompleted -= workerCompleted;
        };
    backgroundWorker.RunWorkerCompleted += workerCompleted;

    backgroundWorker.RunWorkerAsync();
}

x

  1. I imagine that I really need to remove the handler to avoid leak or something. Right?
  2. Witch is the best, access the BackgroundWorker instance trought the "s" parameter or by the variable backgroundWorker?Is it the same?
like image 279
Vitor Canova Avatar asked Dec 10 '25 13:12

Vitor Canova


1 Answers

There is no need to remove the handler, unless you are reusing the same BackgroundWorker instance somewhere else. However, given that you are surrounding it with a Using, this shouldn't be a problem (the scope of your worker is the using statement in this case).

Also, access to the backgroundWorker instance should work either way, however, when cycling data around I often like to use the userState instead which comes back in the RunWorkerCompletedEventArgs.

like image 168
ale Avatar answered Dec 12 '25 01:12

ale



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!