0
0
CsharpConceptBeginner · 3 min read

What is Memory Leak in C#: Explanation and Example

A memory leak in C# happens when the program keeps using memory without freeing it, causing the app to use more memory than needed. This usually occurs when objects are no longer needed but still referenced, so the garbage collector cannot remove them.
⚙️

How It Works

Imagine your computer's memory as a desk where you do your work. When you finish using a paper, you throw it away to keep the desk clean. In C#, the garbage collector acts like a cleaner that removes papers (objects) you no longer need.

A memory leak happens when you keep piling up papers on your desk without throwing them away because you still have a finger holding onto them. Even if you don't need those papers anymore, the cleaner can't remove them because they seem in use. Over time, your desk gets cluttered, making it hard to work.

In programming terms, if your code keeps references to objects that are no longer useful, the garbage collector won't free that memory, causing the program to use more memory than necessary, which can slow down or crash your app.

💻

Example

This example shows a simple memory leak caused by an event handler that is not removed, keeping the object alive.

csharp
using System;

class Publisher
{
    public event EventHandler OnChange;

    public void RaiseEvent()
    {
        OnChange?.Invoke(this, EventArgs.Empty);
    }
}

class Subscriber
{
    public Subscriber(Publisher pub)
    {
        pub.OnChange += HandleEvent;
    }

    void HandleEvent(object sender, EventArgs e)
    {
        Console.WriteLine("Event received.");
    }
}

class Program
{
    static void Main()
    {
        Publisher pub = new Publisher();

        for (int i = 0; i < 1000; i++)
        {
            Subscriber sub = new Subscriber(pub);
            // Subscriber is never unsubscribed, causing memory leak
        }

        Console.WriteLine("Subscribers created.");
    }
}
Output
Subscribers created.
🎯

When to Use

Understanding memory leaks is important when building long-running C# applications like web servers, desktop apps, or services. You want to avoid memory leaks to keep your app fast and stable.

Memory leaks often happen when you subscribe to events but forget to unsubscribe, or when you keep references to large objects longer than needed. Detecting and fixing leaks helps prevent crashes and slowdowns.

Key Points

  • A memory leak means memory is used but never freed.
  • In C#, leaks happen when objects are still referenced but not needed.
  • Event handlers are a common cause if not unsubscribed.
  • Leaks can slow or crash your app over time.
  • Use tools like profilers to find and fix leaks.

Key Takeaways

Memory leaks occur when unused objects remain referenced and are not garbage collected.
Event subscriptions without proper unsubscription are a common source of leaks in C#.
Avoid memory leaks to keep applications running smoothly and efficiently.
Use memory profiling tools to detect and fix leaks early.
Always release resources and unsubscribe from events when no longer needed.