2

Let's say I dynamically create a timer like this:

        System.Timers.Timer expirationTimer = new Timer(expiration * 60000);
        expirationTimer.Elapsed += (sender, e) => removeExpiredCacheEntry(sessionID);
        expirationTimer.Start();

When that reference goes out of scope, will the Timer object be garbage collected? If so, will the event still fire? If not, then how would I avoid a memory leak in this situation?

Thanks!

nw.
  • 4,795
  • 8
  • 37
  • 42

2 Answers2

2

Once the object goes out of scope, and there are no additional references to it. It will, eventually, be garbage collected. But this might not happen for a while. So, the timer will likely keep firing until it is eventaully garbage collected.

This is just a guess though, as I don't have the ability to test it at the moment.

UPDATE:

I just wrote a small test program that looks something like this:

static void Main(string[] args)
{
    SetTimer();
    Console.ReadLine();
}

private static void SetTimer()
{
    Timer expirationTimer = new Timer(1000);
    expirationTimer.Elapsed += (sender, e) => Notify(e);
    expirationTimer.Start();
}

private static void Notify(ElapsedEventArgs e)
{
    Console.WriteLine(string.Format("Notified! {0}", e.SignalTime));   
}

The timer keeps firing for a long time (i eventually just ended the program). Interestingly enough, i inserted a 15 second sleep in the main function, then called GC.Collect() and the timer kept running even after the forced garbage collection, although there is no guarantee that calling GC.Collect() will actually do anything.

I also tried wrapping the timer in a using statement, and that correctly disabled the timer right away (did not print anything to the screen). So, I believe my assumption is correct that garbage collection will eventually collect the timer, and dispose of it. but there is no way to determine when that will be.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
  • Thanks! I ended up just passing the timer itself along to the event handler, which should keep it from being garbage collected and lets me directly call Dispose() on it. – nw. Apr 22 '11 at 23:04
2

According to this answer, the timer object will indeed be eligible for garbage collection and cease to fire events at some point.

However, garbage collection is prevented the other way around. If we have

publisher.SomeEvent += target.SomeHandler;

then "publisher" will keep "target" alive, but "target" will not keep "publisher" alive.

Community
  • 1
  • 1
angularsen
  • 8,160
  • 1
  • 69
  • 83