Would subscribing to my own C# event create a memory leak?

爷,独闯天下 提交于 2021-02-10 06:39:26

问题


If a base class publishes a C# event and a derived class subscribes to it -- i.e. subscribes to itself --. Will the event subscription prevent the object from being garbage collected? Or is the garbage collector smart enough to detect such circular reference situations.

At first glance, it seems like it should but I'm pretty sure I've seen control code that does this. This is such a fundamental question I can't believe I've never looked into it before.

Edit: For Juan R. I mean something like this. (Never compiled this code, just typed it off the top of my head so I might have typos/errors)

public class Base
{ 
    event EventHandler<double>   ValueChanged;
}

public class Derived : Base
{
    public Derived()
    {
        // Will this prevent my object from being collected?

        ValueChanged += OnValueChanged;
    }
    private void OnValueChanged(object sender, double v) => 
    {
    }

}

回答1:


An object subscribing to its own event will not cause a memory leak for the simple reason that the CLR GC is based on reachability, not reference counting. If the object is reachable from a GC root, then it was not eligible for GC anyway. And if it's not reachable, then a self-reference does not make it reachable. There is nothing special about events with regard to GCing circular references.



来源:https://stackoverflow.com/questions/59492705/would-subscribing-to-my-own-c-sharp-event-create-a-memory-leak

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!