BackgroundWorker with anonymous methods?

Mohammad Dayyan picture Mohammad Dayyan · Jan 16, 2010 · Viewed 17.4k times · Source

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.

Answer

Lee picture Lee · Jan 16, 2010

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