我应该在 Dispose() 方法中调用 GC.Collect() 吗?

Should I call GC.Collect() in Dispose() method?

我的示例代码:

using System;
namespace Program
{
    class Test : IDisposable
    {
        public long Loop()
        {
            for (int i = 0; i < 10000; i++)
            {
                var t = new Test();
            }
            return GC.GetTotalMemory(false);
        }
        public void Dispose()
        {
            GC.Collect();
        }
    }

    class MainClass
    {
        static void Main()
        {
            Console.WriteLine("Memory used: " + GC.GetTotalMemory(false));

            using (var t = new Test())
            {
                long size = t.Loop();
                Console.WriteLine("Memory used: " + size);
            }

            //object "t" and variable "size" cannot be re-used here
            //GC.Collect() should be called automatically

            Console.WriteLine("Memory used: " + GC.GetTotalMemory(false));
        }
    }
}

结果是:

Memory used: 29868

Memory used: 160940

Memory used: 30712

如果我在 Dispose 方法中删除 GC.Collect(),结果可能是:

Memory used: 29868

Memory used: 160940

Memory used: 160940

我不明白为什么在我 运行 using 语句后 GC.Collect() 没有自动启动?

你能给我一个理由吗?

还有一个子问题:如果我想在 Dispose 方法中调用 GC.Collect() 是否有必要?

dispose 从未自动调用垃圾收集器,dispose 设计用于释放非托管资源。垃圾收集器执行是预定的进程,将在指定时间后 运行。

当你调用 .Net 垃圾收集器时,它会调用垃圾收集对象的 Object.Finalize 方法来释放管理资源,这就是你的内存使用计数显示较少的原因