In the following code, a Timer
is declared inside a function, where it also subscribes to the Elapsed
event:
void StartTimer()
{
System.Timers.Timer timer = new System.Timers.Timer(1000);
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.AutoReset = false;
timer.Start();
}
Once the function completes, the reference to the Timer
is lost (I presume).
Does the Elapsed
event get unregistered automatically as the object is destroyed, or if not, can the event be unregistered in the Elapsed event itself:
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
var timer = (System.Timers.Timer)sender;
timer.Elapsed -= timer_Elapsed;
}
Would this approach still allow proper cleanup of the object, or should timers never be declared in the local scope of a function for this reason?