Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Difference between GC.GetTotalMemory(false) and GC.GetTotalMemory(true)

Tags:

.net

Could some one tell me the difference between GC.GetTotalMemory(false) and GC.GetTotalMemory(true);

I have a small program and when i compared the results the first loop gives an put put < loop count 0 Diff = 32 > for GC.GetTotalMemory(true); and < loop count 0 Diff = 0 > for GC.GetTotalMemory(false); but shouldnt it be the otherway ?

Smilarly rest of the loops prints some numbers ,which are different for both case. what does this number indicate .why is it changing as the loop increase.

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace test
{   
   struct Address
   {
       public string Street;
   }
   class Details
   {
      public string Name ;
      public Address address = new Address();

   }
   class emp :IDisposable
   {
       public Details objb = new Details();       
       bool disposed = false;
       #region IDisposable Members
       public void Dispose()
       {
           Disposing(true);
       }
       void Disposing(bool disposing)
       {
           if (!disposed)
               disposed = disposing;
           objb = null;           
           GC.SuppressFinalize(this);
       }

       #endregion
   }


    class Program
    {       
        static void Main(string[] args)
        {        
           long size1 = GC.GetTotalMemory(false);
           emp empobj = null;          
           for (int i = 0; i < 200;i++ )
           {
              // using (empobj = new emp()) //------- (1)
               {
                   empobj = new emp(); //------- (2)
                   empobj.objb.Name = "ssssssssssssssssss";
                   empobj.objb.address.Street = "asdfasdfasdfasdf";
               }

              long size2 = GC.GetTotalMemory(false);             
              Console.WriteLine( "loop count " +i + "  Diff = " +(size2-size1));

           }
        }

    }
}
like image 376
somaraj Avatar asked Jan 22 '23 07:01

somaraj


1 Answers

The parameter defines whether or not to wait till a full garbage collection happens before running or not.

See GC.GetTotalMemory(Boolean) Method:

Parameters

forceFullCollection

Type: System.Boolean
true to indicate that this method can wait for garbage collection to > occur before returning; otherwise, false.

The reason that diff is still 0 could be because a GC already happend even if you pass false.

like image 155
Dror Helper Avatar answered Jan 24 '23 20:01

Dror Helper