I have this extension method to disable a timer after a given interval. Is there a guarantee that GC won’t destroy the disableTimer variable (which is local variable in this method)? or is there a justification why this code will work in an hour from now.
timer.DisableAfter(1.Hours()) :
public static void DisableAfter(this Timer timer, TimeSpan timeSpan)
{
var disableTimer = new Timer(timeSpan.TotalMilliseconds)
{
AutoReset = false,
};
disableTimer.Elapsed += (sender, e) =>
{
timer.Stop();
disableTimer.Stop();
};
disableTimer.Start();
}
There’s no garauntee it’ll be garbage collected or not, but if you don’t keep a reference to the timer it’s certainly qualifies for collection.
See this MSDN page for Timer, go down to the first example source block, read the text above and obviously the source block itself… it’s actually all about Timer’s being garbage collected.
http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx