Reputation: 105
I just wanted to ask a rather basic question about events and the garbage collection. I know that the publisher of an event retains a reference to the listening object and thus this can prevent the listening object from being collected.
I wanted to ask what happens in a case like this:
public class Example
{
private CustomObjectThatPublishesEvent foo = new CustomObjectThatPublishesEvent();
public Example()
{
foo.CustomEvent += (inSender, inArgs) => { Console.Write("I know what you did!"); };
}
}
The question here is: Does this cause a problem with the garbage collection? Do I need, as far as garbage collection is concerned, to unsubscribe to this event?
Thank you!
Upvotes: 1
Views: 147
Reputation: 71144
No, you do not normally need to if you know that CustomObjectThatPublishesEvent
does not leak to the heap.
Underlying each event is a field, something like private CustomObjectThatPublishesEvent _CustomEvent
. The event handler is added to that delegate.
The CustomObjectThatPublishesEvent
object holds a reference to the delegate, the delegate holds a reference to the Example
object.
When GC happens, the GC engine will graph out all links to objects, starting at the roots it holds (such as the stack and static fields), marking all objects in use. The remaining ones are deleted.
In this case, neither the Example
object, nor the event handler, nor the CustomObjectThatPublishesEvent
object, are referenced linked to a root object, so they will be deleted.
It may be better to remove the handler anyway if you can, just to keep best practice.
But I certainly wouldn't make the object IDisposable
just to handle that.
If you do not know for certain that CustomObjectThatPublishesEvent
does not leak itself to the heap (via a static variable, even indirectly) then you must do so.
Upvotes: 3