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,

  1. In our system we have low physical memory space then garbage collection is required.
  2. 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.
  3. If we called GC.Collect() method explicitly in our program.

Phases of garbage collection

There are three phases of garbage collection:

  1. 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.
  2. 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.
  3. 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

  1. C# - GC.MaxGeneration Property with Example
  2. C# - GC.GetTotalMemory() Method with Example
  3. C# - GC.Collect() Method with Example
  4. C# - GC.GetGeneration() Method with Example


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.