0

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;
}
folibis
  • 12,048
  • 6
  • 54
  • 97
  • Possible duplicate of [C# Pass Lambda Expression as Method Parameter](http://stackoverflow.com/questions/14297633/c-sharp-pass-lambda-expression-as-method-parameter) – Enfyve Oct 26 '16 at 10:53
  • Your code has a `Func f` type which you are calling with a string. This won't compile as `f` is a function which takes nothing and returns a string. You need `Action f`. – Sean Oct 26 '16 at 10:53
  • Assign it to a variable and pass it as a parameter `Action obj = Console.WriteLine; bw.RunWorkerAsync(obj);` Yes, you need `Action` not `Func` – Semuserable Oct 26 '16 at 10:55

1 Answers1

2

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");
}
Sean
  • 60,939
  • 11
  • 97
  • 136
  • 1
    Thanks, @Sean that's exactly what I need. And yes, I've written `Func` just for example to describe my target. – folibis Oct 26 '16 at 11:01