Garbage collector and event handlers

让人想犯罪 __ 提交于 2019-12-30 04:36:06

问题


A quick question. Say that I have a class implemented as in below example.

class Subscriber
{
    private Publisher publisher = new Publisher;


    public Subscriber()
    {
       publisher.SomeEvent += new EventHandler(OnEventFired);
    }

    private void OnEventFired(object sender, EventArgs e)
    {
    }

}

And somewhere in the program I have a method that looks like this:

public void DoSomething()
{
    Subscriber subscriber = new Subscriber();
}

Am I right to expect that this would cause a memory leak since subscriber never unsubscribes from publishers event, thus resulting in them both maintaining strong reference to each other?


回答1:


It wouldn't cause a leak - the GC can handle circular references with no problems.

However, it would mean that the publisher would effectively have a reference to the subscriber, so the subscriber couldn't be garbage collected until either the publisher is eligible for GC, or it unsubscribes from the event.




回答2:


If during the GC lifetime of an event publisher, an arbitrarily large number of event subscribers may be brought into existence and abandoned without being unsubscribed, such dangling subscriptions will constitute a memory leak. If the event publisher will become eligible for garbage collection around the time the subscribers are abandoned or, at worst, there is for each publisher a bounded number of subscribers that may be created and abandoned, there is no memory leak.

One of my peeves with .net is that Microsoft does not facilitate event cleanup. This is particularly annoying in vb.net, which assures that changing a "WithEvents" variable will properly generate the proper subscriptions and unsubsriptions, but provides no convenient way for an IDisposable handler to unsubscribe all events held by an object.



来源:https://stackoverflow.com/questions/6677785/garbage-collector-and-event-handlers

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