简体   繁体   中英

.net C# garbage-collection question

I have simple question about .net garbage collection. 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 .

Dangling event handlers are the number one cause for memory leaks in .NET applications.

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).

The purpose of the GC is so that you don't have to worry about when things get collected. 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. 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

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