I've just stumbled across some code that uses the GC.KeepAlive()
method and I am trying to understand how it works. For example, in this code:
Timer timer = new System.Timers.Timer(5000);
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
timer.Enabled = true;
GC.KeepAlive(timer);
In this code, my understanding is that a Timer object is created, which spawns a thread that runs every 5 seconds. Next, the GC line is ran. Then the method exits, destroying the timer when garbage collection runs.
The KeepAlive only keeps it alive prior to the call to KeepAlive, which it looks to me is about 0.0000001 seconds and it won't be destroyed there anyway since there is a local reference to it (unless it's destroying it because nothing else happens to the timer object?)
Either way, by the time the 5000 interval is hit the method will have ended ages ago and it's very likely the timer is destroyed. So what's the purpose of that line?