Sobes.tech
Middle

How does garbage collection work in .NET?

sobes.tech AI

Answer from AI

In .NET, garbage collection (GC) is performed automatically by the Common Language Runtime (CLR) based on several factors:

  • Object generations: .NET uses generational garbage collection (Gen 0, Gen 1, Gen 2). Objects are initially created in Gen 0, and if they survive collection, they are promoted to older generations.

  • Trigger conditions: GC is triggered when:

    • There is not enough free memory to allocate new objects.
    • The application explicitly calls GC.Collect() (rarely recommended).
    • The system experiences memory pressure.
  • GC modes:

    • Workstation GC — optimized for client applications, minimizes latency.
    • Server GC — optimized for server applications, uses multiple threads for parallel collection.

Example of explicit garbage collection call (not recommended unless necessary):

GC.Collect();
GC.WaitForPendingFinalizers();

However, it is generally better to trust automatic memory management and avoid manual intervention.

How does garbage collection work in .NET? — C# - sobes.tech