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:
myTimer.Tick -= new EventHandler(ev);
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:
Timer myTimer = new Timer(); // Windows.Forms Timer
public void addEvent(EventHandler ev)
{
myTimer.Tick += ev;
}
public void removeEvent(EventHandler ev)
{
myTimer.Tick -= ev;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With