0

I've following C# code in my WPF application and have a question on detaching the event.

public class Publisher
{
    public event EventHandler Completed;
    public void Process()
    {
        // do something
        if (Completed != null)
        {
            Completed(this, EventArgs.Empty);
        }
    }
}

public class Subscriber
{
    public void Handler(object sender, EventArgs args) { }
}

Usage:

Publisher pub = new Publisher();
Subscriber sub = new Subscriber();
pub.Completed += sub.Handler;
// this will invoke the event
pub.Process();

My question here is, if I dont unsubscribe the handler method and set objects to null using following lines of code, would it cause any memory leak in the application?

pub.Completed -= sub.Handler
pub=null;sub=null;
Max Pringle
  • 621
  • 6
  • 18
Manish K
  • 65
  • 7
  • No, not in that snippet. The Publisher object is only referenced by the local variable of the method that contains the code. So as soon as pub.Publish() runs to completion, both objects can be garbage collected at the same time. A publisher that outlives its subscribers for much longer is a more troublesome scenario. – Hans Passant Sep 06 '17 at 18:49

2 Answers2

1

While an event handler is subscribed, the publisher of the event holds a reference to the subscriber via the event handler delegate (assuming the delegate is an instance method).

If the publisher lives longer than the subscriber, then it will keep the subscriber alive even when there are no other references to the subscriber.

If you unsubscribe from the event with an equal handler, then yes, that will remove the handler and the possible leak.

This was found as an answer to a previous question. Therefore I cannot take credit for it.

Max Pringle
  • 621
  • 6
  • 18
0

Agree with Max Pringle

Please consider usage of WeakEventManager if you cannot determine when delegates should be unsubscribed.

rraszewski
  • 1,135
  • 7
  • 21