tags:

views:

313

answers:

1

Say I have a object Client that has a child StatusType object. Both implement INotifyPropertyChanged.

The Client subscribes to the prop changed event in the property after checking for null and making sure value is different

public StatusType Status
{
    get { return _status ?? (_status = this.GetNewStatusType()); }
    set
    {
        if (!(_status ?? (_status = this.GetNewStatusType())).Equals(value))
        {
            _status.PropertyChanged -= Status_PropertyChanged;
            _status = value;
            _status.PropertyChanged += Status_PropertyChanged;
            base.OnPropertyChanged("Status"); 
        }
    }
}

Client listens for property changed events and bubbles it up.

void Status_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
     base.OnPropertyChanged("Status." + e.PropertyName);
}

Both Client and StatusType inherit from EntitiesBase, which does the actual heavy lifting of implementing INotifyPropertyChanged.

So my actual question is do I need have Client unsubscribe from StatusType.PropertyChanged event for memory reasons? If so, should I use a deconstructor, or have client implement IDisposable?

If I was to use a deconstructor, would it look something like this?

~Client()
{
    if (_status != null)
    {
        _status.PropertyChanged -= Status_PropertyChanged;
        _status = null;
    }
}

Thanks in advance. There are times in our application where we might have over 1000 clients in memory and I want to make sure I am being efficient.

+1  A: 

You could be creating a memory leak if these clients remain in memory indefinitely and their AppDomain is never unloaded. IDisposable might be a better route as you will have a deterministic approach to cleaning up the handlers you no longer need.

[Edit] Keep in mind that even though you may remove the delegate from the event's invocation list you will not free up the memory until the GC runs.

Also this might be of interest to you: http://msdn.microsoft.com/en-us/library/aa970850.aspx

Andrew Hare