Question about GC and event handlers [duplicate]
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, i开发者_StackOverflown 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 GCHandle
object, 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.
No code anywhere will be holding a reference to timer
; therefore it will be eligible for garbage collection.
The timer
object itself has a reference to your timer_Tick
method, but that doesn't matter. It can still be collected.
The GC will collect it at his next crawl... It is like any other object. The timer is referencing to the event, not the event to the instance, so it will be GC'd.
精彩评论