订阅我自己的C#事件会造成内存泄漏吗? [英] Would subscribing to my own C# event create a memory leak?
问题描述
如果基类发布了C#事件,而派生类订阅了它(即,订阅了它自己).事件订阅会阻止对象被垃圾回收吗?还是垃圾收集器足够聪明,可以检测到这种循环引用情况.
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.
对于Juan R.我的意思是这样的.(永远不要编译此代码,只需将其打在我的头上,这样我就可能出现错别字/错误)
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) =>
{
}
}
推荐答案
预订对象本身的事件不会导致内存泄漏,原因很简单,原因是CLR GC基于可访问性而不是引用计数.如果可以从GC根目录访问该对象,则无论如何该对象都不适合使用GC.而且,如果无法访问,则自引用不会使它可访问.关于 GCing循环引用的事件没有什么特别的.
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.
这篇关于订阅我自己的C#事件会造成内存泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!