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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With