Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
OOPS in C#
C# Data Types
Boxing and Unboxing in C#
Garbage Collection in C#
C# - Conditional Statements
C# - Loops
Interfaces in C#
Generics in C#
Collections in C#
C# 8.0 new features
C# Singleton Design Pattern
C# Factory Design Pattern
LINQ in C#
C# - Program to Find Prime Numbers
C# - Fibonacci Sequence
C# - Factorial of a number
C# - Recursive methods
C# - Anonymous Methods
C# - String Methods
C# TDD - XUnit
C# TDD - NUnit
C# Multiton Design Pattern
C# Facade Design Pattern
C# Abstract Factory Design Pattern
C# Decorator Design Pattern
C# Composite Design Pattern

Garbage Collection in C#



Garbage Collection (GC) in C# is an automated process that manages the allocation and release of memory within the .NET runtime environment. Its purpose is to clean up and free memory that is no longer in use by the application, helping to prevent memory leaks and enhance overall performance.

How Garbage Collection Works:

Garbage Collection in C# relies on a system of managed memory and involves a few key stages:

  1. Allocation:

    • When new objects are created, they are stored in a region of memory called the managed heap.

  2. Marking Phase:

    • The GC starts by identifying which objects are still in use (rooted) and which aren't. It traverses the references from the root (e.g., static variables, local variables on stack) to find all reachable objects.

  3. Moving Phase:

    • The GC then compacts the heap by relocating the reachable objects to a contiguous region of memory.

    • This step helps to eliminate fragmentation, making larger blocks of memory available for future allocations.

  4. Sweeping Phase:

    • Finally, the GC reclaims the memory occupied by unreferenced objects.

Generations:

The GC organizes objects into three generations to optimize performance:

  • Generation 0: For short-lived objects, such as temporary variables.

  • Generation 1: For objects that have survived one garbage collection.

  • Generation 2: For long-lived objects, like static data or objects that survive multiple collections.

Objects in lower generations are collected more frequently as they are expected to have shorter life spans.

Triggering Garbage Collection:

Garbage Collection in .NET is usually initiated automatically, but you can also manually trigger it using the GC.Collect() method when necessary. However, manual invocation is typically discouraged as it can negatively impact performance.

Example Code:

Here's a simple example illustrating object creation and garbage collection:

csharp
using System;

class Program
{
    static void Main()
    {
        // Create objects
        for (int i = 0; i < 100; i++)
        {
            Person person = new Person("John Doe");
        }

        // Force garbage collection (not recommended in practice)
        GC.Collect();
        
        // Wait for user input 
        Console.ReadLine();
    }
}

class Person
{
    public string Name { get; private set; }

    public Person(string name)
    {
        Name = name;
    }

    // Destructor (finalizer)
    ~Person()
    {
        Console.WriteLine("Person object is being finalized.");
    }
}

In this example, we're creating Person objects within a loop. When the method GC.Collect() is called, garbage collection will be forced, and any unreferenced Person objects will be finalized and their memory reclaimed.

Key Considerations:

  • Avoid Forced GC: It's generally best to let the runtime handle garbage collection to avoid performance issues.

  • Use IDisposable Interface: For objects that consume unmanaged resources, implement the IDisposable interface and override the Dispose() method to release these resources explicitly.

  • Memory Management: Good programming practices, such as minimizing object references and promptly releasing resources, can help the GC work more efficiently.

Garbage Collection in C# provides a robust and efficient way to manage memory, freeing developers from the need to manually allocate and deallocate memory. It helps improve application performance and reliability by automatically cleaning up unused resources.

If you have any more questions or need further explanation, feel free to ask!




All rights reserved | Privacy Policy | Sitemap