How free memory used by a large list in C#?(C# 中的大列表使用了多少空闲内存?)
问题描述
我有一个名为 Population 的列表,它包含了很多职位,但在某些时候我会停止使用它.如何释放资源?那么这是部分代码:
I have a list called Population, is a great list of very many positions and at some point I stop using it. How I can free the resources?
Then this is part of the code:
private List <BasePopulation> Population=new List <BasePopulation>();
Population.SomeMethod();
Population.Clear();
我使用了 Clear 方法,但不起作用.有什么想法吗?
I used the Clear method, but not works. Any idea?
推荐答案
问题可能是 Clear 没有按照你的想法做.Clear 只是将 List 标记为空,而无需调整它在后台使用的内部数组的大小.但是,它将删除对单个 BasePopulation 实例的所有引用.因此,如果没有其他数据结构引用它们,它们将有资格进行垃圾收集.但是,它不会直接减小 List 的大小.我刚刚使用 ILSpy 验证了这一点.
The problem may be that Clear is not doing what you think it is. Clear simply marks the List as being empty without resizing the internal array that it uses behind the scenes. It will, however, remove all references to the individual BasePopulation instances. So if no other data structure has a reference to them they will be eligible for garbage collection. But, it will not reduce the size of the List directly. I just verified this using ILSpy.
你有两个选择.
设置
Population = null.这将取消整个对象实例的根,使其符合垃圾回收条件.
Set
Population = null. This will unroot the entire object instance making it eligible for garbage collection.
在这个 List 上调用 TrimExcess.这将调整内部数组的大小.
Call TrimExcess on this List. This will resize the internal array.
这篇关于C# 中的大列表使用了多少空闲内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 中的大列表使用了多少空闲内存?
基础教程推荐
- WPF 模态进度窗口 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
