Garbage collectors and event handlers

Quick question. Let's say that I have a class implemented as shown below.

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(); } 

Can this be expected to cause a memory leak, since the subscriber never cancels the subscription to the publishers event, which leads to the fact that they both maintain a strong link to each other?

+7
garbage-collection c # events
source share
2 answers

This will not cause a leak - the GC can handle circular references without any problems.

However, this would mean that the publisher would actually have a link to the subscriber, so the subscriber could not collect garbage until the publisher could receive the GC, or he would unsubscribe from the event.

+15
source share

If an arbitrarily large number of event subscribers can be created and canceled during the life of a GC publisher, without unsubscribing, such dangling subscriptions will constitute a memory leak. If the publisher of the event receives the right to collect garbage at the time that subscribers are left or, in the worst case, there is a limited number of subscribers for each publisher that can be created and left, there is no memory leak.

One of my peeves with .net is that Microsoft is not making event cleaning easy. This is especially annoying for vb.net, which ensures that changing the "WithEvents" variable will correctly generate the correct subscriptions and unsubsriptions, but it does not provide a convenient way for the IDisposable handler to unsubscribe from all events stored in the object.

+2
source share

All Articles