According to MSDN, the reference to System.Threading.Timer must be stored otherwise, it will receive garbage collection. Therefore, if I run this code, it does not 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 a little while keeping the timer in a temporary local variable, it will survive and write a message:
public static void RunTimer() { var timer = new Timer(s => Console.WriteLine("Hello")); timer.Change(TimeSpan.FromSeconds(1), TimeSpan.Zero); }
During garbage collection, there seems to be no way to access the timer from root or static objects. So can you explain why the timer survives? Where is this link saved?
Peter Smolinsky
source share