views:

298

answers:

3

Hi,
I'm gonna create a BackgroundWorker with an anonymous method.
I've written the following code :

BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork += new DoWorkEventHandler(
    () =>
    {
        int i = 0;
        foreach (var item in query2)
        {
            ....
            ....
        }
    }
);


But Delegate 'System.ComponentModel.DoWorkEventHandler' does not take '0' arguments and I have to pass two objects to the anonymous method : object sender, DoWorkEventArgs e

Could you please guide me, how I can do it ? Thanks.

+4  A: 

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 { ... }
Lee
@Jader: Edited so that it's the equivalent of my answer. Why not just vote my answer up?
Kent Boogaart
+5  A: 

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
{
    ...
};

HTH,
Kent

Kent Boogaart
+1  A: 

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) => ...
Aggelos Mpimpoudis