Search code examples
c#.netbackgroundworkeranonymous-methods

BackgroundWorker with anonymous methods?


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.


Solution

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