C#  

Learn Garbage Collection in C#

Concept Overview

Garbage Collection (GC) in C# is the automatic process of freeing up memory by removing objects that are no longer in use. This helps prevent memory leaks and ensures that your web application runs smoothly even under heavy load.

In ASP.NET WebForms, each request can create objects (e.g., file readers, database connections, temporary data). Once those objects are no longer needed, GC automatically reclaims memory — without you manually freeing it.

Real-Time Example Scenario

Imagine a report generation web page that creates many temporary objects in memory (like strings, lists, etc.) while processing.
Once the report is generated and sent to the user, those objects are no longer needed — this is where the Garbage Collector comes in to reclaim that memory automatically.

We’ll simulate this by:

  • Creating temporary objects

  • Checking memory usage before and after forcing garbage collection

  • Displaying results on the web page

ASP.NET WebForms Example

File: GarbageCollectionDemo.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GarbageCollectionDemo.aspx.cs" Inherits="WebApp.GarbageCollectionDemo" %>

<!DOCTYPE html>
<html>
<head>
    <title>Garbage Collection in ASP.NET WebForms</title>
</head>
<body>
    <form id="form1" runat="server">
        <h2>Garbage Collection Example in C# (ASP.NET WebForms)</h2>
        <asp:Button ID="btnSimulate" runat="server" Text="Simulate Garbage Collection" OnClick="btnSimulate_Click" />
        <br /><br />
        <asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
    </form>
</body>
</html>

File: GarbageCollectionDemo.aspx.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace WebApp
{
    public partial class GarbageCollectionDemo : System.Web.UI.Page
    {
        protected void btnSimulate_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            // 1. Show memory before creating objects
            long before = GC.GetTotalMemory(false);
            sb.Append($"<b>Memory before object creation:</b> {before:N0} bytes<br/>");

            // 2. Create a large list to simulate memory usage
            List<byte[]> tempData = new List<byte[]>();
            for (int i = 0; i < 500; i++)
            {
                tempData.Add(new byte[1024 * 100]); // 100 KB each × 500 = 50 MB approx
            }

            long afterCreate = GC.GetTotalMemory(false);
            sb.Append($"<b>Memory after object creation:</b> {afterCreate:N0} bytes<br/>");

            // 3. Release reference (eligible for garbage collection)
            tempData = null;

            // 4. Force garbage collection
            GC.Collect();
            GC.WaitForPendingFinalizers();

            long afterGC = GC.GetTotalMemory(true);
            sb.Append($"<b>Memory after garbage collection:</b> {afterGC:N0} bytes<br/>");

            // 5. Display which generation is collected
            sb.Append("<br/><b>Garbage Collector Generations:</b><br/>");
            sb.Append($"Max Generation Supported: {GC.MaxGeneration}<br/>");
            sb.Append($"Generation of string object: {GC.GetGeneration(sb)}<br/>");

            lblResult.Text = sb.ToString();
        }
    }
}

Expected Output

When you click “Simulate Garbage Collection”, you’ll see something like:

Memory before object creation: 25,000 bytes
Memory after object creation: 52,184,000 bytes
Memory after garbage collection: 26,400 bytes
Garbage Collector Generations:
Max Generation Supported: 2
Generation of string object: 0

This clearly shows how GC cleaned up unused objects and freed memory.

How This Works

StepDescription
1. Create objectsSimulates temporary data or large memory use (like report generation or caching)
2. Nullify referencesMakes the objects eligible for garbage collection
3. Call GC.Collect()Forces garbage collection manually (usually not recommended in production — just for demo)
4. Memory freedUnused memory is reclaimed automatically

Real-Time Use Cases in WebForms

ScenarioWhere GC Helps
File Uploads/DownloadsLarge file buffers are automatically cleared after the request
Report GenerationTemporary data (DataTables, lists) released post-response
Session ExpiryObjects in memory are automatically reclaimed after the session timeout
Image ProcessingLarge image objects are released automatically after disposal

Best Practices

  • Avoid forcing garbage collection manually (use GC.Collect() only for testing).

  • Dispose of unmanaged resources (like file handles or DB connections) using using blocks.

  • Use memory profiling tools in large applications to monitor heap usage