Fog Creek Software
Discussion Board

Welcome! and rules

Joel on Software

GC and Timers

I've got the following code

    private void TimerHandler( object sender, System.Timers.ElapsedEventArgs e )
      System.Diagnostics.Debug.WriteLine( "Timer triggered!" );

    private void btnDoIt_Click( object sender, System.EventArgs e)
      System.Timers.Timer lTimer = new System.Timers.Timer( 1000 );
      System.Timers.ElapsedEventHandler lHandler = new System.Timers.ElapsedEventHandler( this .TimerHandler );
      lTimer.Elapsed += lHandler;
      lTimer.AutoReset = false ;
      lTimer.Enabled = true ;

The timer and handler would appear to go out of scope at the of the click handler so I'm not sure how longer they're going kick around from.

In practice it seems like the timer isn't actually destroyed until its finished (I've tried kicking the GC with GC.Collect and debug and release builds). But there doesn't seem to be anything stated explicitly about whether the timer could be destroyed before it triggers. Anyone know definitively whether the timer is guaranteed not to be killed before triggering if I don't keep a reference to it?

Similarly with threads, if they are running and I don't have a reference, will they be GC'ed?

Thanks in advance

Ian Glover
Wednesday, June 1, 2005

In your specific case, you're using server-based timer, so it won't be GC'ed even if you don't have a reference to it.

But the lightweight System.Threading.Timer class will be GC'ed:
"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."

And the Windows-based System.Windows.Forms.Timer class won't be GC'ed:
"If the timer is disabled and the timer is out of scope, the timer will be disposed when garbage collection occurs. If the timer is enabled, even if it is out of scope, it is not subject to garbage collection."

For more information, here's a couple of MSDN articles comparing the 3 timer types in the .NET Framework:

Mark Pearce
Wednesday, June 1, 2005

*  Recent Topics

*  Fog Creek Home