According to MSDN, a reference to System.Threading.Timer should be kept otherwise it will get garbage-collected. So if I run this code, it doesn't write any message (which is the expected behavior):
static void Main(string[] args)
{
RunTimer();
GC.Collect();
Console.ReadKey();
}
public static void RunTimer()
{
new Timer(s => Console.WriteLine("Hello"), null, TimeSpan.FromSeconds(1), TimeSpan.Zero);
}
However, if I modify the code slightly by storing the timer in a temporary local variable, it survives and writes the message:
public static void RunTimer()
{
var timer = new Timer(s => Console.WriteLine("Hello"));
timer.Change(TimeSpan.FromSeconds(1), TimeSpan.Zero);
}
During garbage collection, there is apparently no way how to access the timer from root or static objects. So can you please explain why the timer survives? Where is the reference preserved?