简体   繁体   English

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

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

My example code: 我的示例代码:

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

Result was: 结果是:

Memory used: 29868 使用的内存:29868

Memory used: 160940 使用的内存:160940

Memory used: 30712 使用的内存:30712

If I remove GC.Collect() in Dispose method, the result maybe: 如果我在Dispose方法中删除GC.Collect() ,则结果可能是:

Memory used: 29868 使用的内存:29868

Memory used: 160940 使用的内存:160940

Memory used: 160940 使用的内存:160940

I don't understand why doesn't GC.Collect() start automatically after I run the using statement? 我不明白为什么在运行using语句后GC.Collect()无法自动启动?

Can you give me a reason? 你能给我个理由吗?

And a sub-question: Is it necessary if I wanna call GC.Collect() in Dispose method? 还有一个子问题:是否需要在Dispose方法中调用GC.Collect()

The dispose never called Garbage Collector automatically, the dispose design to free un-managed resource. 处置从未自动调用Garbage Collector,处置设计释放了非托管资源。 The Garbage Collector execution is scheduled processes which will run in after specified time. 垃圾收集器执行是计划的进程,将在指定时间后运行。

When you call .Net Garbage Collector, it calls the Object.Finalize method of an object on garbage collection to free manage resource, that's why your memory use count show less number 当您调用.Net Garbage Collector时,它将调用垃圾回收上对象的Object.Finalize方法以释放管理资源,这就是为什么您的内存使用量显示较少的原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM