Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 721
L.E.O Avatar asked Jul 13 '11 10:07

L.E.O


1 Answers

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.

like image 118
Jon Skeet Avatar answered Oct 10 '22 00:10

Jon Skeet