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

I want to know the best way to do this:

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

  • I guess I really need to remove the handler to avoid a leak or something else. Correctly?
  • Witch is the best, access to an instance of BackgroundWorker caused by the s parameter or the backgroundWorker variable? It is the same?
+3
source share
2 answers

1) What do you mean? Delete "doWorkHandler"? If so, you do not need to do this (as far as I know). Just like Ale , you just need to reuse the same bgw.

. , bgw , .


2) ( ). "" "s", , . s ( ).


- . . goo ( , , ). =)

+1

, BackgroundWorker . , , , ( using.)

, backgroundWorker , , userState, RunWorkerCompletedEventArgs.

+2

Source: https://habr.com/ru/post/1796094/


All Articles