My question is simple, why GC can’t figure it out that timer object in the main should be garbage collected along with the timer inside TestTimer and associated EventHandler?
Why am I continously getting console.Writeline output?
class Program
{
public static void Main()
{
TestTimer timer = new TestTimer();
timer = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Console.ReadKey();
}
}
public class TestTimer
{
private Timer timer;
public TestTimer()
{
timer = new Timer(1000);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
private void timer_Elapsed(Object sender, ElapsedEventArgs args)
{
Console.Write("\n" + DateTime.Now);
}
}
Don’t depend on the GC, use the Dispose pattern to properly dispose the
TestTimer(which then should dispose theTimer).However, what happens is that the timer keeps itself alive by getting a GC handle on itself. Read this blog post:
http://nitoprograms.blogspot.com/2011/07/systemthreadingtimer-constructor-and.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+blogspot%2FOlZtT+%28Nito+Programming%29