Possible Duplicates:
Timer, event and garbage collection : am I missing something ?
If I’d have the following code:
public void SomeMethod()
{
Timer timer = new Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
will timer_Tick continue to be repeatedly called after the SomeMethod has finished even though there is no reference to the timer anywhere?
I’m thinking maybe it will until the Timer’s Dispose method is called. But then, in general, does the GC knows when an object have not been disposed?
Contrary to the other answers here, no, the timer will not be garbage collected.
Internally, enabling the timer will allocate a
GCHandleobject, which will keep the object, and thus the timer, and thus whatever object has the implementing event handler(s) alive until you disable it, or the program ends, whichever comes first.This has already been answered here on SO, here: Timer, event and garbage collection : am I missing something ?, so I’m going to close this question as a duplicate.