Signum
Signum

Reputation: 875

Avoiding memory leaks with events

class Subscriber
{
    private Publisher _publisher;

    void SomeMethod()
    {
        _publisher = new Publisher();
        _publisher.SomeEvent += HandleEvent;
    }

    void HandleEvent(object sender, EventArgs e)
    {

    }
}

class Publisher
{
    public event EventHandler SomeEvent;

    void FireEvent()
    {
        SomeEvent?.Invoke(this, EventArgs.Empty);
    }
}

Do I need to detach HandleEvent from SomeEvent to avoid memory leak? Subscriber lives longer than Publisher, so my understanding is that when Publisher gets disposed, it will also clear all event handlers from SomeEvent, so there shouldn't be any references left. Am I right?

Upvotes: 1

Views: 88

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273264

Subscriber lives longer than Publisher

That means you are OK, no need to complicate things with an unsubscribe.

The statement _publisher.SomeEvent += HandleEvent; creates a (somewhat hidden) reference from _publisher to its owner. That would prevent the owning Subscriber from being collected, but only when the publisher outlives it.

Since _publisher is private, the cleanup is implicit. You do not have to (should not) add IDisposable here. That is, not for managing the events.

And since you tagged this WinForms: all those eventhandlers (eg Button1_Click) all create references from a Control to the owning Form, no need for cleanup there either.

Upvotes: 3

Related Questions