BennoDual
BennoDual

Reputation: 6259

Is there a MemoryLeak?

I load a List of LiefItems.

List<LiefItem> list = this.LoadLiefItems();

LiefItem is implementing INotifyPropertyChanged on this way:

public event PropertyChangedEventHandler PropertyChanged;

[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(string propertyName) {
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null) {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

After loading the List, I am subscribing to PropertyChanged:

foreach(var item in list) {
    item.PropertyChanged += ItemOnPropertyChanged;
}

After, the List will be used as a ItemsSource of a DataGrid.

I asking me now, if load the list a second time and set the new List as ItemsSource of my DataGrid, are the first loaded items removed from the Memory or does I have a MemoryLeak because I am subscribing to PropertyChanged and don't unsubscribe?

Upvotes: 1

Views: 582

Answers (1)

Ella Cohen
Ella Cohen

Reputation: 1405

No memory leak there.

C# events implement subject-observer pattern underneath.

When an event is raised, what actually happens underneath is a call to the member method of the object that was registered to the event.

So, if you do something like:

 item.PropertyChanged += ItemOnPropertyChanged;

This is equivalent to:

 item.PropertyChanged += this.ItemOnPropertyChanged;

And when the event is triggered, there's an invocation of that method:

registeredObject.ItemOnPropertyChanged(propertyName);

This means that a reference is stored for the object which registered for the event. Not the object that raises the event.

Upvotes: 5

Related Questions