Garbage Collection in C# | .NET Framework

Garbage Collection in .NET makes possible automatic memory management. Memory space appears when a class object appears. After completing all the object’s actions, the memory space allocated to the object is a waste. It is the reason why Garbage Collection is useful. It releases the memory space when it is not required. Garbage Collection has internally an engine named Optimization engine.

When does GC work?

Garbage Collection, when at least one of the following conditions is satisfied.

  • When the memory required for a particular project exceeds the available memory
  • When the system has low physical memory
  • When the developer calls the GC method, it happens only in special conditions because GC runs automatically.

Garbage Collection Example

The heap memory organized into three generations allows handling various objects during Garbage Collection.

  • Generation 0: all the objects such as temporary variables contained in generation 0. Generation 0 contains all short-lived objects.
  • Generation 1: the objects from generation 0, not released in the garbage collection, run, pass to generation 1. Generation 1 is a buffer between short-lived objects in generation 0 and the long-lived objects in generation 2.
  • Generation 2: the space occupied by the object in generation 1, not released in the garbage collection run; the objects pass to generation 2. There are static objects, and they remain in the heap memory during the process duration.

MS framework system has the Garbage Collection class. Here is the MaxGeneration.

MaxGeneration

using system;

class GCExample1 

    public static void Main(string[] args) 

    { 

        try 

        { 

            Console.WriteLine(“GC Maximum Generations:” + GC.MaxGeneration); 

        } 

        catch (Exception oEx) 

        { 

            Console.WriteLine(“Error:” + oEx.Message); 

        } 

    } 

MaxGeneration Property returns the highest generation in the GC. It is the total number of generations in the Garbage Collection beginning from 0. If it returns 2, that means three generations in the GC. These are Generation 0, Generation 1, and Generation 2.

GetTotalMemory

It shows the memory occupied by various resources. I added a managed code object in the heap memory to increase the memory size. The GetGeneration method finds the managed object in which generation:
Total Memory: 141744
BaseGC Generation is: 0
Total memory: 149936

CollectionCount and Collect

CollectionCount helps to find the generation garbage collection that occurred. There are three generations in the GC. Initially, the argument was 0. Through the code, we collected the unused objects in generation 0. We checked the CollectionCount in generation 0. Is says 1. The Collect method collects unreferenced objects in the heap memory. It clears the object and reclaims the memory space.