简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM