C# 即使在GC.Collect()之后也不会收集内存
我多次执行下面的代码,即使在垃圾收集之后,也总是得到12字节的内存差异。任何人都可以帮助我,为什么下面的代码总是保持内存中的12字节C# 即使在GC.Collect()之后也不会收集内存,c#,memory-leaks,garbage-collection,C#,Memory Leaks,Garbage Collection,我多次执行下面的代码,即使在垃圾收集之后,也总是得到12字节的内存差异。任何人都可以帮助我,为什么下面的代码总是保持内存中的12字节 internal class Test { private List<int> _arrItems; //private int[] _arrItems; public Test() { _arrItems = new List<int>(); // _arrItems
internal class Test
{
private List<int> _arrItems;
//private int[] _arrItems;
public Test()
{
_arrItems = new List<int>();
// _arrItems = new int[0];
}
internal void Close()
{
_arrItems = null;
}
private static void Main(string[] args)
{
var totalMemoryBefore = GC.GetTotalMemory(true);
{
var test = new Test();
test.Close();
test = null;
}
GC.Collect();
GC.WaitForFullGCComplete();
var totalMemory = GC.GetTotalMemory(true);
Console.WriteLine(totalMemoryBefore + ":All Done:" + totalMemory);
Console.ReadLine();
}
}
内部类测试
{
私人物品清单;
//私有int[]\u项目;
公开考试()
{
_arrItems=新列表();
//_arrpitems=新整数[0];
}
内部无效关闭()
{
_arrpitems=null;
}
私有静态void Main(字符串[]args)
{
var totalMemoryBefore=GC.GetTotalMemory(true);
{
var测试=新测试();
test.Close();
test=null;
}
GC.Collect();
GC.WaitForFullGCComplete();
var totalMemory=GC.GetTotalMemory(true);
Console.WriteLine(totalMemoryBefore+”:全部完成:“+totalMemory”;
Console.ReadLine();
}
}
提前感谢。我找到了原因,原因是List类中的静态只读成员 在System.Generic.Collection.List类中定义的静态成员:
static readonly T[] _emptyArray = new T[0];
GC.Collect(2,GCCollectionMode.Forced)怎么样代码>?文档清楚地表明,此函数返回的数字是一个猜测。我认为在一个受管理的、垃圾收集的环境中,您不能依赖精确的(字节)内存值。我只是猜测,但框架本身可能会分配这些字节。为了得到更好的想法,在分配之前和之后获得一个完整的进程转储,然后使用一些内存分析器工具比较它们。(WinDbg或.Net内存分析器等)你真的打算用12字节的内存做什么?可能是因为您的代码触发了一些CLR内部基础结构代码来分配一些内存。请注意,在.Net世界中,并非只有您一人;GC、CLR、Jit编译器,它们都可以自己分配内存。