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?
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With