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!
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
then “publisher” will keep “target” alive, but “target” will not keep “publisher” alive.