sriesch

I have created and started a thread timer in the application event sub "myapplication_startup" using the following code:

Dim TheThreadTimerStateObj As New ThreadTimerStateObj

Dim TimerDelegate As New Threading.TimerCallback(AddressOf TheThreadTimerStateObj.ThreadTimerTask)

TheThreadTimerStateObj.TimerReference = New System.Threading.Timer(TimerDelegate, TheThreadTimerStateObj, 5000, 5000)

And here is the object definition:

Public Class ThreadTimerStateObj

Public TimerReference As System.Threading.Timer

<irrelevant code not pictured>

Public Sub ThreadTimerTask(ByVal ThreadTimerStateObj As Object) <...bleah bleah...> End Sub

End Class

I stored a reference to the new System.Threading.Timer object (created by the 3rd line of code) within my ThreadTimerStateObj class so that the garbage collector wouldn't destroy the new timer after I exited the sub, and it seems to be working.

THE QUESTION: Must I also save a reference somewhere to the new ThreadTimerStateObj object "TheThreadTimerStateObj" to prevent it from eventually being destroyed, or is a reference already being saved internally somehow when TheThreadTimerStateObj.ThreadTimerTask is passed as an argument to create the new System.Threading.Timer



Re: Visual Basic Language thread timers and garbage collection

Riquel Dong ĘC MSFT

Hi,

Based on your post, I think you ought to save a reference to ThreadTimerStateObj. If the application has not any reference to ThreadTimerStateObj . It will be collected by garbage collection.

You pass the ThreadTimerStateObj to Timer contructor. It acts as an object containing information to be used by the callback method. You can pass null reference ( VB nothing) to constuctor. 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.

At last you have wrote the code. you can do not save reference to ThreadTimerStateObj. You will see the result of your application.

Hope this can help you !

Riquel






Re: Visual Basic Language thread timers and garbage collection

sriesch

Ok, thanks, I will do that.