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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With