Manish K
Manish K

Reputation: 65

Detaching the events

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;

Upvotes: 0

Views: 45

Answers (2)

rraszewski
rraszewski

Reputation: 1145

Agree with Max Pringle

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

Upvotes: 0

Max Pringle
Max Pringle

Reputation: 639

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.

Upvotes: 1

Related Questions