Tân
Tân

Reputation: 1

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

Memory used: 160940

Memory used: 30712

If I remove GC.Collect() in Dispose method, the result maybe:

Memory used: 29868

Memory used: 160940

Memory used: 160940

I don't understand why doesn't GC.Collect() start automatically after I run the using statement?

Can you give me a reason?

And a sub-question: Is it necessary if I wanna call GC.Collect() in Dispose method?

Upvotes: 1

Views: 2075

Answers (1)

Avinash Jain
Avinash Jain

Reputation: 7606

The dispose never called Garbage Collector automatically, the dispose design to free un-managed resource. 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

Upvotes: 1

Related Questions