GC收集并等待,但仍使用内存?

时间:2018-03-02 07:39:01

标签: c# garbage-collection

我们都知道这应该是强制垃圾收集的方式

public class MemoryUsage
{
    private byte[] mmr;
    public MemoryUsage()
    {
        mmr = new byte[10000000]; // ~10 MB
    }

    ~MemoryUsage()
    {
        Console.WriteLine("Finalizer");
    }
}

public static void Main()
{
    Console.WriteLine(String.Format("Initial memory usage: {0}", GC.GetTotalMemory(false)));

    MemoryUsage m1 = new MemoryUsage();
    MemoryUsage m2 = new MemoryUsage();
    MemoryUsage m3 = new MemoryUsage();

    Console.WriteLine(String.Format("I use memory: {0}", GC.GetTotalMemory(false)));
    m1 = null;
    m2 = null;
    m3 = null;

    GC.Collect();
    GC.WaitForPendingFinalizers();

    Console.WriteLine(String.Format("I did collect and waited, but memory still: {0}", GC.GetTotalMemory(false)));

    GC.GetTotalMemory(true);

    Console.WriteLine(String.Format("I only got amount of memory and: {0}", GC.GetTotalMemory(false)));
}

此外,C#允许我们检查当前使用的内存量。

Initial memory usage: 47568
I use memory: 30062576
Finalizer
Finalizer
Finalizer
I did collect and waited, but memory still: 30070520
I only got amount of memory and: 62184

但是当我调用两个collect和wait方法时,然后使用内存我仍然看到内存没有被清除。

{{1}}

App内置于发布模式,结果为:

{{1}}

我发现只能调用GC.GetTotalMemory(true)而不是WaitForPendingFinalizers,所有终结器都已完成。

还有其他方法可以确保GC完成吗?感谢

0 个答案:

没有答案