即使在GC.Collect()之后也没有收集内存

时间:2015-02-18 20:35:16

标签: c# memory-leaks garbage-collection

我多次执行下面的代码,即使在垃圾收集后也总是得到12个字节的内存差异。任何人都可以帮助我,为什么下面的代码总是在内存中保留12个字节。

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();
    }
}

提前致谢。

1 个答案:

答案 0 :(得分:3)

我找到了原因,Reason是List类中的静态只读成员。

在System.Generic.Collection.List&lt;&gt;中定义的静态成员类:

static readonly T[]  _emptyArray = new T[0];