垃圾收集和控件已订阅事件的本地变量 [英] Garbage Collection and local variables to whose events a control has subscribed

查看:100
本文介绍了垃圾收集和控件已订阅事件的本地变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个c#类声明了一个变量,比如说一个ObservableCollection,然后
订阅了该变量上的一个事件,这是否会阻止该控件被垃圾收集。换句话说,在以下情况下,类SomeClass可用于垃圾收集:

  public class SomeClass 
{
private ObservableCollection< string> _someCollection = new ObservableCollection< string>();

public SomeClass()
{
_someCollection.CollectionChanged + = OnSomeCollectionCollectionChanged;
}

private void OnSomeCollectionCollectionChanged(object sender,NotifyCollectionChangedEventArgs e)
{
}
}


解决方案

假设没有别的引用 ObservableCollection ,然而,如果其他内容保持 ObservableCollection 活着,那么引用从集合到 SomeClass 实例(通过事件)将使 SomeClass 对象保持活动状态。



编辑:澄清评论... GC非常有能力收集两个彼此相互引用的对象,只要没有别的东西指向它们。例如:

  / ----> ---- \ 
X ----> ; ---- YZ
(root)\ ---- <---- /

这里对象X充当一个根,也就是说垃圾回收器知道应该保持活动状态(例如,它是从线程堆栈中的局部变量引用的,或者它是通过一个静态变量引用的)。



现在想象一下,从X到Y的引用被切断了:

  / ----> ---- \ 
XYZ
(root)\ ----< ---- /
$ / code>

现在X仍然作为GC根存活,但没有提到的活对象Y或Z,所以他们都可以被垃圾收集。他们相互引用的事实是无关紧要的。


If a c# class declares a variable, say an ObservableCollection, and subsequently subscribes to an event on that variable, does that prevent the control from being garbage collected. In other words, in the following circumstance, is the class SomeClass available for garbage collection:

public class SomeClass
{
    private ObservableCollection<string> _someCollection = new ObservableCollection<string>();

    public SomeClass()
    {
        _someCollection.CollectionChanged += OnSomeCollectionCollectionChanged;
    }

    private void OnSomeCollectionCollectionChanged(object sender,NotifyCollectionChangedEventArgs e )
    {
    }
}

解决方案

Assuming nothing else has a reference to the ObservableCollection, both of them will be eligible for garbage collection.

However, if something else keeps the ObservableCollection alive, the reference from the collection to the SomeClass instance (via the event) will keep the SomeClass object alive too.

EDIT: To clarify the comments... the GC is quite capable of collecting two object which refer to each other, so long as nothing else is referring to them. For example:

               /---->----\
  X ---->---- Y           Z
(root)         \----<----/

Here object "X" is acting as a root, i.e. it's something the garbage collector knows should be kept alive (e.g. it's referred to from a local variable in a stack from of thread, or it's referred to via a static variable).

Now imagine that the reference from X to Y is severed:

               /---->----\
  X           Y           Z
(root)         \----<----/

Now X is still kept alive as a GC root, but there are no "live" objects which refer to either Y or Z, so they can both be garbage collected. The fact that they refer to each other is irrelevant.

这篇关于垃圾收集和控件已订阅事件的本地变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆