Remove all Timer Tick event handlers

In my application, I can have one or more subscribers to a particular Timer's Tick event. They are added using the normal syntax:

myTimer.Tick += new EventHandler(...);

Given the nature of my program, at any given time I will not know exactly how many subscribers my Tick Event has, and which methods they are. But I want to be able to remove all currently subscribed events at one go. I therefore cannot use the codemyTimer.Tick -= new EventHandler(...) because I cannot be certain of the method names.

I know I could just try and unsubscribe every possible method in a try ... catch block but I want a more elegant solution.

Any ideas?

[685 byte] By [Phizz] at [2007-12-16]
# 1
Use a collection to keep track...and use the add method of the collection to set up your eventhandler...this way each handler will be indexed and you can do something like this:

MyEventHandlerCollection.Clear

DMan1 at 2007-9-9 > top of Msdn Tech,Windows Forms,Windows Forms General...
# 2

Two ideas:
use the Enabled property
wrap the timer in your own class by inheriting from it, add your own event handler list.


[DefaultEvent("MyTick")]

public class MyTimer : System.Windows.Forms.Timer {

public MyTimer(IContainer components) : base(components) {}

private static object EventMyTick = new object();

protected override void OnTick(EventArgs e) {

EventHandler eh = Events[EventMyTick] as EventHandler;
if (eh != null) {
eh(
this,EventArgs.Empty);
}

}
public event EventHandler MyTick {
add { Events.AddHandler(EventMyTick,
value); }
remove { Events.RemoveHandler(EventMyTick,
value); }
}

// hide from code and propgrid
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]public new event EventHandler Tick {
add {
base.Tick += value; }
remove {
base.Tick -= value; }
}

public void ClearAllEventHandlers() {
Events.Dispose();
}

}




Hope this helps
- Jessica

Jessica at 2007-9-9 > top of Msdn Tech,Windows Forms,Windows Forms General...