I\'m gonna create a BackgroundWorker with an anonymous method.
I\'ve written the following code :
BackgroundWorker bgw = new B
You just need to add parameters to the anonymous function:
bgw.DoWork += (sender, e) => { ... }
Or if you don't care about the parameters you can just:
bgw.DoWork += delegate { ... }
If you have written the above without lambdas how it would be?
backgroundWorker1.DoWork +=
new DoWorkEventHandler(backgroundWorker1_DoWork);
and the named method:
private void backgroundWorker1_DoWork(object sender,
DoWorkEventArgs e)
{
// Get the BackgroundWorker that raised this event.
BackgroundWorker worker = sender as BackgroundWorker;
// Assign the result of the computation
// to the Result property of the DoWorkEventArgs
// object. This is will be available to the
// RunWorkerCompleted eventhandler.
e.Result = ComputeFibonacci((int)e.Argument, worker, e);
}
But now you are using lambdas with no bound variables ()=> You should provide two objects sender and e (which they will get type inferred later).
backgroundWorker1.DoWork += (sender, e) => ...
Lambda expressions are really handy to make the code shorter and more readable. However entry level programmers might find it a bit difficult to deal with. There are three separate concepts one should go through: anonymous methods, delegates and lambda expressions. A detailed walk-through of each of them is beyond the scope of this answer. I hope that the code example given below will serve the purpose of giving a quick view of the different approaches available.
class TestBed
{
BackgroundWorker bgw = new BackgroundWorker();
void sample()
{
//approach #1
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
//DoWorkEventHandler is nothing but a readily available delegate written by smart Microsoft guys
//approach #2, to make it a little shorter
bgw.DoWork += (s,e) =>
{
//...
};
//this is called lambda expression (see the => symbol)
//approach #3, if lambda scares you
bgw.DoWork += delegate
{
//... (but you can't have parameters in this approach
};
//approach #4, have a helper method to prepare the background worker
prepareBgw((s,e)=>
{
//...
}
);
//approach #5, helper along with a simple delegate, but no params possible
prepareBgw(delegate
{
//...
}
);
//approach #6, helper along with passing the methodname as a delegate
prepareBgw(bgw_DoWork);
//approach #7, helper method applied on approach #1
prepareBgw(new DoWorkEventHandler(bgw_DoWork));
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
//...
}
void prepareBgw(DoWorkEventHandler doWork)
{
bgw.DoWork+= doWork;
}
}
Note that we used "delegate" and not "Delegate" in this example (there is a difference between the two)
If you specify a lambda, you must ensure it takes the same number of arguments:
bgw.DoWork += (s, e) => ...;
But if you're not using the arguments, you could just use an anonymous delegate without parameters:
bgw.DoWork += delegate
{
...
};