Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsubscribe from events in observableCollection

Tags:

c#

Lets say I have an observableCollection of classes:

CustomClassName testClass = new CustomClassName();
ObservableCollection<CustomClassName> collection = new ObservableCollection<CustomClassName>();
testClass.SomeEvent += OnSomeEvent;
collection.add(testClass);

When I will remove items from a collection, do i need manually unsubscribe from events(OnSomeEvent) or should I leave it for a GC? And what is the best way to unsubscribe?

like image 944
Sasha Avatar asked Aug 13 '15 06:08

Sasha


1 Answers

If you expect your item to be collected then yes you need to unsubscribe.

To do so, the usual way is:

collection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(collection_CollectionChanged);

// ...
// and add the method
void collection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
    if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
    {
        foreach (var it in e.OldItems) {
            var custclass = it as CustomClassName;
            if (custclass != null) custclass.SomeEvent -= OnSomeEvent;
        }
    }
}
like image 200
tafia Avatar answered Oct 19 '22 20:10

tafia