All posts

Fix Memory Leak in .NET

Diagnose and fix memory leaks in .NET applications, covering event handler leaks, IDisposable patterns, and large object heap issues.

Memory Leaks in .NET

The garbage collector handles most memory management in .NET, but certain patterns prevent objects from being collected. Here are the most common leaks.

Event Handler Leaks

The classic .NET memory leak — subscribing to events without unsubscribing:

// LEAK: publisher holds a reference to subscriber
public class Dashboard
{
    public Dashboard(DataService service)
    {
        service.DataChanged += OnDataChanged; // Never unsubscribed
    }

    private void OnDataChanged(object sender, EventArgs e) { }
}

// FIX: implement IDisposable
public class Dashboard : IDisposable
{
    private readonly DataService _service;

    public Dashboard(DataService service)
    {
        _service = service;
        _service.DataChanged += OnDataChanged;
    }

    public void Dispose()
    {
        _service.DataChanged -= OnDataChanged;
    }
}

HttpClient Misuse

Creating new HttpClient instances per request exhausts socket handles:

// BAD
public async Task<string> GetData()
{
    using var client = new HttpClient(); // Socket exhaustion
    return await client.GetStringAsync("https://api.example.com/data");
}

// GOOD — use IHttpClientFactory
services.AddHttpClient<MyService>();

Static Collections

// LEAK: grows without bound
public static class Cache
{
    private static readonly Dictionary<string, object> _items = new();
    public static void Add(string key, object value) => _items[key] = value;
}

// FIX: use MemoryCache with expiration
services.AddMemoryCache();

Diagnosing with dotnet-dump

dotnet-dump collect -p <pid>
dotnet-dump analyze <dump-file>
> dumpheap -stat

Bugsly monitors .NET process memory and captures exceptions when memory thresholds are crossed, providing heap snapshots for analysis.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free