我一直在研究如何避免因 View 模型中对 INotifyCollectionChanged
事件的强引用而导致的内存泄漏。我正在尝试使用 ListCollectionView
看看它是否适合我。我认为以下是内存泄漏,我做错了吗?
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();
}
最佳答案
ListCollectionView
的文档不是很好,但如果您注意到有一个方法 DetachFromSourceCollection
。此调用的备注中提到取消订阅和允许垃圾回收。
var stuff = new ObservableCollection<string>();
while (true)
{
ListCollectionView result = new ListCollectionView(stuff);
//Use this method to unsubscribe to events on the underlying collection and allow the CollectionView to be garbage collected.
result.DetachFromSourceCollection();
//When finished set to null
result = null;
GC.Collect();
}
关于c# - ListCollectionView 是否泄漏内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5749403/