Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# adding and removing events from a timer

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?

like image 557
TK. Avatar asked Feb 16 '09 17:02

TK.


1 Answers

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.

like image 108
atoumey Avatar answered Sep 23 '22 06:09

atoumey