Software/C#.Net
Understanding Object Lifetime
charom
2011. 5. 18. 05:29
Understanding Object Generations
• Generation 0: Identifies a newly allocated object that has never been marked for collection.
• Generation 1: Identifies an object that has survived a garbage collection (i.e., it was marked for collection but was not removed due to the fact that the sufficient heap space was acquired).
• Generation 2: Identifies an object that has survived more than one sweep of the garbage collector.
Select Members of the System.GC Type
Select Members of the System.GC Type
AddMemoryPressure() RemoveMemoryPressure() |
Allows you to specify a numerical value that represents the calling object’s “urgency level” regarding the garbage collection process. Be aware that these methods should alter pressure in tandem and thus never remove more pressure than the total amount you have added. |
Collect() | Forces the GC to perform a garbage collection. This method has been overloaded to specify a generation to collect, as well as the mode of collection (via the GCCollectionMode enumeration). |
CollectionCount() | Returns a numerical value representing how many times a given generation has been swept. |
GetGeneration() | Returns the generation to which an object currently belongs |
GetTotalMemory() | Returns the estimated amount of memory (in bytes) currently allocated on the managed heap. A Boolean parameter specifies whether the call should wait for garbage collection to occur before returning |
MaxGeneration | Returns the maximum number of generations supported on the target system. Under Microsoft’s .NET 4.0, there are three possible generations: 0, 1, and 2. |
SuppressFinalize() | Sets a flag indicating that the specified object should not have its Finalize() method called |
WaitForPendingFinalizers() | Suspends the current thread until all finalizable objects have been finalized. This method is typically called directly after invoking GC.Collect() |
static void Main(string[] args) { Console.WriteLine("***** Fun with System.GC *****"); // Print out estimated number of bytes on heap. Console.WriteLine("Estimated bytes on heap: {0}", GC.GetTotalMemory(false)); // MaxGeneration is zero based, so add 1 for display purposes Console.WriteLine("This OS has {0} object generations.\n", (GC.MaxGeneration + 1)); Car refToMyCar = new Car("Zippy", 100); Console.WriteLine(refToMyCar.ToString()); // Print out generation of refToMyCar object. Console.WriteLine("Generation of refToMyCar is: {0}", GC.GetGeneration(refToMyCar)); Console.ReadLine(); }