c# - Pass lambda expression/anonymous method into BackgroundWorker -
suppose have backgroundworker
in code. want pass anonymous function/delegate in @ start. code bellow want 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
the error:
cannot convert anonymous method type 'object' because not delegate type
or
cannot convert lambda expression type 'object' because not delegate type
so how can passinto lambda expression/anonymous method backgroundworker
?
here code in c describe 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; }
you need assign lambda variable , pass in:
action<string> action = (string txt) => console.writeline(txt); bw.runworkerasync(action);
note i've used action<>
code takes data , doesn't return anything. dowork
handler wrong , should this:
bw.dowork += (object sender, doworkeventargs e) => { action<string> f = (action<string>)e.argument; f("step one"); ... f("step two"); }
Comments
Post a Comment