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# 中的大列表使用了多少空闲内存?


基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01