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 doWorkHa开发者_Go百科ndler = 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 imagine that I really need to remove the handler to avoid leak or something. Right?
- Witch is the best, access the BackgroundWorker instance trought the "s" parameter or by the variable backgroundWorker?Is it the same?
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.
1) What do you mean exactly? To remove the "doWorkHandler"? If so, you don't need to do that (as far as I know). Just as Ale said, you just need that to reuse the same bgw.
But for the using, I wouldn't go that way. Just my way of implementing but for bgw I would stick with a variable contained within the class.
2) Access will work fine both ways (general use). It's "better" to use the "s" but you'll have to typecast everything so the code will become harder to read. Personally I would use the variable declaration instead (direct access) instead of the "s" object.
Now, there's something new. Take a gook look at the Task library. Might be a goo way to go (I've found that many times it's better and easier than using the Background Worker). And you can build parallel tasks as well =)
精彩评论