Keep system.threading.timer from being GC (garbage collected)

jayy66

Newcomer
Joined
Aug 24, 2006
Messages
14
Location
texas
Does anyone know how to keep a threading.timer from being garbage collected? The timer works fine and mutiple threads are usually running without any problems, however, when the GC is executed the timers are disposed of. Anybody have any ideas?

Code:
Dim timerDelegate As Threading.TimerCallback = AddressOf Me.SendFaxResponse
checkInboxTimer = New System.Threading.Timer(timerDelegate, Nothing, 60000, 20000)
 
Where is the above code being run from? (button click, form load etc.)
If the variables timerDelegate and checkInboxTimer are only declared within a single routine then they will go out of scope and be eligble for collection as soon as the routine exits.
 
The code is being run from a class method and checkInboxTimer is a class variable. The class is question is instantiate in the form load of the main form.
What I getting from your post is that once the program exits the class the timer will be subject to GC.

How can I prevent this from happening?
 
Simply put, you need to store a reference to the timer. It doesn't matter where. If there is a specific class that uses it then that class should keep a reference to it and as long as the class as referenced the timer is referenced.

The fail-safe method would be to store the timer in a static variable, which will never be garbage collected until the application closes.
 
Back
Top