I've been investigating how to avoid memory leaks caused by strong references to the INotifyCollectionChanged
event from a view model. I was playing around with using a ListCollectionView
to see if that would deal with it for me. I think that the following is leaking memory, am I doing something wrong?
var stuff = new ObservableCollection<string>();
while (true)
{
var result = new ListCollectionView(stuff);
// Just to keep make sure that the memory I'm seeing
// isn't waiting to be GC'd
GC.Collect();
}
I initially posted this as a comment, but I think it makes a better answer, so ...
a) if you're sure you've found a problem with the .NET framework, you're probably doing something wrong. It's not impossible, it's just not likely. b) that GC.Collect() isn't going to do what you're thinking it will.
I think you need to review how GC.Collect() works.
MSDN GC.Collect Method
Remarks
Use this method to try to reclaim all memory that is inaccessible.
All objects, regardless of how long they have been in memory, are considered for collection; however, objects that are referenced in managed code are not collected. Use this method to force the system to try to reclaim the maximum amount of available memory.
For starters, you don't show us where you're disposing of that memory that the
ListCollectionView(stuff)
. You're just allocating new and allocating new, but you never dispose of the old. So yeah, it's going to leak like crazy. Until the GC runs and tries to collect.If you do the same thing you demonstrate here with a list of strings it will most likely do the same thing. But for what you've shown, I expect it to leak.