简体   繁体   中英

Garbage collector and event handlers

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?

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.

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.

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