Home »
.Net »
C# Programs
C# Garbage Collection (GC Class) Programs
Garbage collection is used for memory management in C#. When we create an object of a class, then it allocates memory in heap area of memory and then does required stuff with objects, then allocated memory of object should be free. Here, garbage collector plays an important role. It releases memory automatically.
Garbage collection is used in the case of managed heap, it has an engine internally that is known as Optimization Engine.
Garbage collection is used when it satisfies at least one of the following conditions are given below,
- In our system we have low physical memory space then garbage collection is required.
- When we creating multiple objects in the heap area, if the memory space of the heap area exceeds a pre-set threshold, then garbage collection is used.
- If we called GC.Collect() method explicitly in our program.
Phases of garbage collection
There are three phases of garbage collection:
- Marking Phase:
In this phase of garbage collection, here a list is prepared for all live objects of the heap area. Deleted objects are not part of the list prepared in this phase.
- Relocating Phase:
In this phase references of all live objects are updated so that it points to the new location where the live objects will be relocated to in the compacting phase.
- Compacting Phase:
In this phase, heap memory will be compacted. Here heap space is released allocated by dead objects. And live objects remaining are moved. After garbage collection live objects are moved towards the older end of the heap.
This section contains various C# programs on Garbage collection or GC class.
List of C# Garbage Collection (GC Class) Programs
- C# - GC.MaxGeneration Property with Example
- C# - GC.GetTotalMemory() Method with Example
- C# - GC.Collect() Method with Example
- C# - GC.GetGeneration() Method with Example