I just gave an answer to a quite simple question by using an extension method. But after writing it down i remembered that you can't unsubscribe a lambda from an event handler.
So far no big problem. But how does all this behave within an extension method??
Below is my code snipped again. So can anyone enlighten me, if this will lead to myriads of timers hanging around in memory if you call this extension method multiple times?
I would say no, cause the scope of the timer is limited within this function. So after leaving it no one else has a reference to this object. I'm just a little unsure, cause we're here within a static function in a static class.
public static class LabelExtensions
{
public static Label BlinkText(this Label label, int duration)
{
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Interval = duration;
timer.Tick += (sender, e) =>
{
timer.Stop();
label.Font = new Font(label.Font, label.Font.Style ^ FontStyle.Bold);
};
label.Font = new Font(label.Font, label.Font.Style | FontStyle.Bold);
timer.Start();
return label;
}
}
Update
Just to clarify i used System.Windows.Forms.Timer. So from your answers it seems, that especially using this timer class just was the right choice cause it does anything the way as i would expect it in this case. If you try another timer class in this case you can run into trouble as Matthew found out. Also i found a way by using WeakReferences if my objects are staying alive or not.
Update 2
After a little sleep and a little more thinking, i also made another change to my tester (answer below) i just added a GC.Collect()
after the last line and set the duration to 10000. After starting the BlinkText()
several times i hitted all the time my button2 to get the current state and to force a garbage collection. And as it seems all the timers will be destroyed after calling the Stop()
method. So also a garbage collection while my BlinkText is already left and the timer is running doesn't lead to any problems.
So after all your good responses and a little more testing i can happily say that it just does what it should without leaving timers in the memory nor throwing away the timers before they done their work.