How does the Collector KeepAlive trash method work with a timer?

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?

+6
source share
2 answers

So what is the purpose of this line?

Nothing. You should not use it, because it helps nothing. This code was probably written by someone unfamiliar with how the Timer class works.

Inside the Timer class, completely different means will be used to ensure that it does not collect garbage before it appears. See this question for more details.

+4
source

In this context, there is no reason for this line. The only time this can help is a lot of code between timer.Enabled and a call to KeepAlive , as in:

  timer.Enabled = true; // lots of code here that does // things that take some time GC.KeepAlive(timer); } 

This will allow the garbage collector to collect a timer before the method ends. Without calling KeepAlive GC may decide that the timer will no longer be used after setting Enabled , and it may perform an early collection.

If you need a constant timer, you must declare it in the class scope.

+1
source

Source: https://habr.com/ru/post/946796/


All Articles