delegates - C# BackgroundWorker Add System.EventHandler to RunWorkerCompleted -
timer timer = new timer(); backgroundworker bw = new backgroundworker(); eventhandler handlestuff = delegate { messagebox.show("handlestuff called"); }; timer.tick += handlestuff; bw.runworkercompleted += handlestuff;
the lastly line not allowed because:
cannot implicitly convert type 'system.eventhandler' 'system.componentmodel.runworkercompletedeventhandler'
2 questions: why can't runworkercompleted take regular eventhandler - completed event isn't multithreaded, there reason restriction exists?
more importantly, there work around accomplish this? want utilize same handler timer.tick
, bw.runworkercompleted
why can't runworkercompleted take regular eventhandler?
because signature doesn't match event. (and delegate isn't equivalent through co/contra-variance). handler always needs of same type event's delegate, definition.
more importantly, there work around accomplish this?
you won't able attach exact handler, in terms of exact reference, no. best can create new event handler of appropriate type who's body nil phone call code want execute:
bw.runworkercompleted += (s,args)=> handlestuff(s,eventargs.empty);
c# delegates backgroundworker eventhandler
No comments:
Post a Comment