A quick question. Say that I have a class implemented as in below example.
class Subscriber
{
private Publisher publisher = new Publisher;
public Subscriber()
开发者_StackOverflow {
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.
精彩评论