I just came across some code that uses the GC.KeepAlive() method, and I'm trying to figure out 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, I understand that a Timer object is created that spawns a thread that starts every 5 seconds. Then the line GC is executed. The method then exits, destroying the timer when the garbage collection starts.
KeepAlive saves it only until the KeepAlive call, which, it seems to me, is about 0.0000001 seconds, and it will not be destroyed there, since there is a local link to it (unless it destroys it, because nothing else happens to the timer object? )
In any case, by the time the interval 5000 is reached, the method will end centuries ago, and it is very likely that the timer will be destroyed. So what is the purpose of this line?
source share