gpt4 book ai didi

c# - ListCollectionView 是否泄漏内存?

转载 作者:可可西里 更新时间:2023-11-01 08:36:46 25 4
gpt4 key购买 nike

我一直在研究如何避免因 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com