简体   繁体   English

.net C#垃圾收集问题

[英].net C# garbage-collection question

I have simple question about .net garbage collection. 我对.net垃圾收集有一个简单的问题。 In the following code I create a listener class instance in the constructor of the child object. 在以下代码中,我在子对象的构造函数中创建了一个侦听器类实例。 My question is does the listener class get collected by the garbage collection before the child or main object since there is no direct reference to it anywhere? 我的问题是,由于在任何地方都没有直接引用,因此在子对象或主对象之前,垃圾收集器会收集侦听器类吗?

class MainObject
{
    public void DoSomething()
    {

    }
}

delegate void someEventHandler();
class ChildObject
{
    public event someEventHandler SomeEvent;
    MainObject main;
    public ChildObject(MainObject main)
    {
        this.main = main;
        new Listener(this, main);
    }
}


class Listener
{
    MainObject main;

    public Listener(ChildObject child, MainObject main)
    {
        this.main = main;
        child.SomeEvent += new someEventHandler(child_SomeEvent);
    }
    void child_SomeEvent()
    {
        main.DoSomething();
    }
}

There is a reference to it, in the invocation list child.SomeEvent . 一个参考吧,在调用列表child.SomeEvent

Dangling event handlers are the number one cause for memory leaks in .NET applications. 悬挂事件处理程序是.NET应用程序中导致内存泄漏的第一大原因。

It will be collected once the child object is collected, but if you want it to be collected before hand you need to remove it from the invocation list (by using the -= operator). 一旦收集了child对象,便会收集该对象,但是如果要先收集它,则需要从调用列表中将其删除(使用-=运算符)。

The purpose of the GC is so that you don't have to worry about when things get collected. GC的目的是让您不必担心何时收集到东西。 They get collected when they're no longer needed and in no particular order. 当不再需要它们并且没有特定顺序时,它们就会被收集。 There is no way to guarantee the collection of one object before another object. 没有办法保证一个对象先于另一个对象的集合。

as Oded said there is a reference to it. 正如Oded所说的那样。 If want to avoid that you can have a look at the Weak Events Pattern that tries to address the memory leak issue: 如果要避免这种情况,可以查看尝试解决内存泄漏问题的弱事件模式:

http://msdn.microsoft.com/en-us/library/aa970850.aspx http://msdn.microsoft.com/en-us/library/aa970850.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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