Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Timers get automatically garbage collected?

When you use a Timer or a Thread that will just run for the entire lifetime of the program do you need to keep a reference to them to prevent them from being garbage collected?

Please put aside the fact that the below program could have timer as a static variable in the class, this is just a toy example to show the issue.

public class Program {     static void Main(string[] args)     {         CreateTimer();          Console.ReadLine();     }      private static void CreateTimer()     {         var program = new Program();          var timer = new Timer();         timer.Elapsed += program.TimerElapsed;         timer.Interval = 30000;         timer.AutoReset = false;         timer.Enabled = true;     }      private void TimerElapsed(object sender, ElapsedEventArgs e)     {         var timerCast = (Timer)sender;          Console.WriteLine("Timer fired at in thread {0}", GetCurrentThreadId());          timerCast.Enabled = true;     }      ~Program()     {         Console.WriteLine("Program Finalized");     }      [DllImport("kernel32.dll")]     static extern uint GetCurrentThreadId(); } 

Could the timer get collected in that above example? I ran it for a while and I never got a exception nor a message saying ~Program() was called.

UPDATE: I found out from this question (thanks sethcran) that threads are tracked by the CLR, but I still would like an answer about Timers.

like image 469
Scott Chamberlain Avatar asked Aug 08 '13 21:08

Scott Chamberlain


People also ask

When you request garbage collector to run it will start to run immediately?

It is not possible to run garbage collection immediately as we are programming in managed environment and only CLR decides when to run garbage collection.

How do you make sure that the garbage collector is done running when you call?

GC. Collect() forces garbage collector to run. This is not recommended but can be used if situations arise.


2 Answers

This is only a problem with the System.Threading.Timer class if you don't otherwise store a reference to it somewhere. It has several constructor overloads, the ones that take the state object are important. The CLR pays attention to that state object. As long as it is referenced somewhere, the CLR keeps the timer in its timer queue and the timer object won't get garbage collected. Most programmers will not use that state object, the MSDN article certainly doesn't explain its role.

System.Timers.Timer is a wrapper for the System.Threading.Timer class, making it easier to use. In particular, it will use that state object and keep a reference to it as long as the timer is enabled.

Note that in your case, the timer's Enabled property is false when it enters your Elapsed event handler because you have AutoReset = false. So the timer is eligible for collection as soon as it enters your event handler. But you stay out of trouble by referencing the sender argument, required to set Enabled back to true. Which makes the jitter report the reference so you don't have a problem.

Do be careful with the Elapsed event handler. Any exception thrown inside that method will be swallowed without a diagnostic. Which also means that you won't set Enabled back to true. You must use try/catch to do something reasonable. If you are not going to intentionally end your program, at a minimum you'll need to let your main program know that something isn't working anymore. Putting Enabled = true in a finally clause can avoid getting the timer garbage collected, but at the risk of having your program throw exceptions over and over again.

like image 199
Hans Passant Avatar answered Oct 04 '22 06:10

Hans Passant


Let's carry out an experiment:

private static void UnderTest() {   // Timer is a local varibale; its callback is local as well   System.Threading.Timer timer = new System.Threading.Timer(     (s) => { MessageBox.Show("Timer!"); },       null,       1000,       1000); } 

...

// Let's perform Garbage Colelction manually:  // we don't want any surprises  // (e.g. system starting collection in the middle of UnderTest() execution) GC.Collect(2, GCCollectionMode.Forced);  UnderTest();  // To delay garbage collection // Thread.Sleep(1500);  // To perform Garbage Collection // GC.Collect(2, GCCollectionMode.Forced); 

So far

  • if we keep commented both Thread.Sleep(1500); and GC.Collect(2, GCCollectionMode.Forced); we'll see message boxes appear: the timer is working
  • if we uncomment GC.Collect(2, GCCollectionMode.Forced); we'll see nothing: the timer starts then it is collected
  • if we uncomment both Thread.Sleep(1500); and GC.Collect(2, GCCollectionMode.Forced); we'll see a single message box: the timer starts, goes off a single message box and then the timer is collected

So System.Threading.Timers are collected as any other object instances.

like image 31
Dmitry Bychenko Avatar answered Oct 04 '22 07:10

Dmitry Bychenko