Thursday, 7 October 2010

System.Threading.Timer and Garbage Collector

I would like to tell you the problem i ran into some time ago with the System.Threading.Timer.

I used this Timer in a software where periodically i have to retrieve data from one or more solar inverters by a serial port.

Well, at first I declared and initialized the timer in a method (the constructor but this is not relevant), so i wrote something like this:

System.Threading.Timer Tim = new System.Threading.Timer(CallbackMethod, null, 0, Milliseconds);

My program started to have a strange problem. When I ran the software it suddenly stops after a while without raising any exception and without crashing.

For a lot of time i was sure that the problem was in the callback, the place where i ask data to the inverter.

But the problem was not there. At the end i read on msdn:

Note

As long as you are using a Timer, you must keep a reference to it. As with any managed object,
a Timer is subject to garbage collection when there are no references to it. The fact that a Timer
is still active does not prevent it from being collected.


So the solution is to declare the Timer outside the method, in the same class or as a static object somewhere else. The important thing is that the Timer object does not go out of scope, otherwise the Garbage collector will remove it from the memory.

This explains also why the program wasn't raising any exception. The callback never references the Timer in no way so it just was not executed.

No comments: