Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reassign event handler at runtime

I would like to change the delegate attached to a BackgroundWorker at runtime. Would something like below work?

DoWorkEvenHandler dweh = new DoWorkEventHandler(method1);
backgroundworker.DoWork += dweh;

and at some point later change the delegate associated with DoWork by reassigning the reference dweh:

dweh = new DoWorkEventHandler(method2);
like image 340
lgp Avatar asked Feb 18 '23 07:02

lgp


1 Answers

No you cannot "assign" a delegate to an event handler. Handlers are attached to events by adding them to the invocation list of an underlying delegate that is used internally to represent the event. This is by design!

And no, you cannot change the handler by changing the object pointed to by a reference that was previously used to attach an event handler; in part because delegates are immutable, and in part because you would just be changing the reference to point to something else, not really changing the event handler which is what you're trying to accomplish.

In order to change the delegate you have to first remove the previous delegate:

backgroundworker.DoWork -= dweh;

Then assign a new one by adding it as a handler of the event:

backgroundworker.DoWork += new DoWorkEventHandler(method2);

Note

In most cases you can remove a handler (delegate) from an event using this syntax:

backgroundworker.DoWork -= new DoWorkEventHandler(mehtod1);

or using an implicit or explicit method group conversion:

backgroundworker.DoWork -= (DoWorkEventHandler)mehtod1;  // explicit convertion    
//  -  or  - 
backgroundworker.DoWork -= mehtod1;                      // implicit (more compact)

But depending on the situation you may need to maintain a reference to the previous delegate in order to be able to remove it later. For example this would apply to anonymous methods or lambda expressions.

like image 103
Mike Dinescu Avatar answered Mar 04 '23 02:03

Mike Dinescu