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();
}
}
}

Join the conversation! Your thoughts help the community grow.