I am trying to add and remove events from a timer and I have the following code:
Timer myTimer = new Timer(); // Windows.Forms Timer public void addEvent(MyDelegate ev) { myTimer.Tick += new EventHandler(ev); } public void removeEvent(MyDelegate ev) { myTimer.Tick -= new EventHandler(ev); }
I don’t know If Im doing anything stupid in trying to add and remove delegates in this fashion, I am able to add delegates and get them to fire as expected. However, when I attempt to remove the events, they continue to fire on Timers Tick.
Can anyone see anything obviously wrong?
I believe that this code:
creates a new EventHandler object. It will never remove an existing EventHandler. To get the functionality you want, you should be passing in EventHandlers, not MyDelegates, to the add and remove methods:
The calling code will have to keep track of the EventHandlers added, so that it can pass in the same EventHandler object when it is time to unsubscribe.