Joe
Joe

Reputation: 6816

PropertyChangedEventManager - Will failing to call RemoveHandler cause a leak?

I am wondering if the code below will produce a leak: Class Parent has a list of class Child. Child objects use PropertyChangedEventManager.AddHandler to be notified of property changes in the aggregating Parent object. If those aggregated instances never call RemoveHandler, will it produce a leak?

I understand that the GC is based upon reachability, not reference counting, but clearly the PropertyChangedEventManager is maintaining a list of handler subscribers somewhere. So how does that list get cleaned up if I don't call RemoveHandler?

Something like this admittedly simplified version of what my code does:

public class Parent : INotifyPropertyChanged
{
    public Parent()
    {
        _children = new List<Child>();
        _children.Add(new Child(this));
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public bool Value
    {
        get => _value;
        set 
        {
            _value = value;
            PropertyChanged?.Invoke(new PropertyChangedEventArgs("Value"));
        }
    }
    private List<Child> _children    
}


public class Child
{
    public Child(Parent parent)
    {
        // Will failing to undo this with RemoveHandler cause a leak?
        PropertyChangedEventManager.AddHandler(r, OnValueChange, "Value");
    }

    void OnValueChanged(object sender, PropertyChangedEventArgs e)
    {
        // Do something...
    }
}

Upvotes: 0

Views: 360

Answers (1)

Oguz Ozgul
Oguz Ozgul

Reputation: 7187

The answer is, no.

As the name of the base type of PropertyChangedEventManager (WeakEventManager) implies, all the handlers registered to the PropertyChangedEventHandler will be kept as Weak References

As you may well know,

A weak reference permits the garbage collector to collect the object while still allowing the application to access the object. A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist

So we can be sure that the class references (the declaring instance of the event handler) will not leak.

RemoveHandler detaches the handler from the event. It removes an entry from the table the property changed event manager maintains to keep track of events and their handlers.

The event manager also has a cleanup process to purge any entries for which the Target of the weak reference has been collected by the GC.

All of this is from reverse engineering starting from: https://referencesource.microsoft.com/#windowsbase/Base/System/ComponentModel/PropertyChangedEventManager.cs

Upvotes: 1

Related Questions