简体   繁体   中英

C# Listen to event of same class member - Garbage Collection

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!

TL;DR;

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.

However:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM