简体   繁体   中英

ObservableCollection not garbage collected unless it is manually set to null

In a WPF app, I have a XAML window which opens up another window and sets its DataContext to an instance of a ViewModel class. Among other things, a ListView in the view is bound to an ObservableCollection in the ViewModel.

The ViewModel loads about 7,000 items when it is initialized, and the ListView displays them (in a VirtualizedStackPanel).

In VS2015's debug performance monitors, I noticed that after the second window is closed, and there are no more references (as far as I know) to the ViewModel that contains the 7,000 items, those items still persist in memory. They survive several garbage collections of generations 0, 1 and 2 (and they are not in the LOH).

After a long investigation, I found out that setting the entier collection of 7,000 items to null when the window is closing, and making sure an OnPropertyChanged event is raised, causes this collection of items to be collected immediately. Trying to follow this collection to its roots in the VS heap snapshot tool is impoosible, since they are supposedly linked to a mess of XAML controls and elements.

My question is: is this normal behavior? Do you have to null out my objects all the time? What could I be missing?

The most likely cause for this is that you have done something inside the second XAML Window View that has subscribed to an event in a non-weak way on the ViewModel. You need not worry about View-to-VM subscriptions done by Windows because these are weak by default so they don't leak. I'd start by looking for Behaviors you have written that might subscribe to VM events for example ObservableCollection.CollectionChanged or ICommand.CanExecuteChanged .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM