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;
}
3
  • Possible duplicate of C# Pass Lambda Expression as Method Parameter Commented Oct 26, 2016 at 10:53
  • Your code has a Func<string> 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<string> f. Commented Oct 26, 2016 at 10:53
  • Assign it to a variable and pass it as a parameter Action<string> obj = Console.WriteLine; bw.RunWorkerAsync(obj); Yes, you need Action<string> not Func<string> Commented Oct 26, 2016 at 10:55

1 Answer 1

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");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, @Sean that's exactly what I need. And yes, I've written Func<string> just for example to describe my target.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.