folibis
folibis

Reputation: 12874

Pass lambda expression/anonymous method into BackgroundWorker

Suppose I have a BackgroundWorker in my code. I want to pass anonymous function/delegate in it at start. The code bellow is what I want to do:

BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (object sender, DoWorkEventArgs e) => {
    Func<string> f = (Func<string>)e.Argument;
    f("step one");
    ...
    f("step two");
}
bw.RunWorkerAsync((string txt) => {Console.WriteLine(txt);} ); // doesn't work
// bw.RunWorkerAsync( delegate(string txt) { Console.WriteLine(txt); })); // doesn't work too

The error:

Cannot convert anonymous method to type 'object' because it is not a delegate type

Or

Cannot convert lambda expression to type 'object' because it is not a delegate type

So how can I passinto lambda expression/anonymous method into BackgroundWorker?

Here is a code in C to describe exactly what I need:

void func(char *ch)
{
    printf("%s", ch);
}

void test( void (* f)(char *) )
{
    f("blabla");
}


int main(int argc, char *argv[])
{
    test(func);
    return 0;
}

Upvotes: 0

Views: 608

Answers (1)

Sean
Sean

Reputation: 62532

You need to assign the lambda to a variable and then pass it in:

Action<string> action = (string txt) => Console.WriteLine(txt);
bw.RunWorkerAsync(action);

Note that I've used an Action<> as your code takes data and doesn't return anything. Your DoWork handler is wrong and should be like this:

bw.DoWork += (object sender, DoWorkEventArgs e) => {
    Action<string> f = (Action<string>)e.Argument;
    f("step one");
    ...
    f("step two");
}

Upvotes: 2

Related Questions