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 -statBugsly 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 FreeRelated Articles
Fix MemoryError in Electron When Deploying
Resolve memory errors when building and packaging Electron apps, covering electron-builder memory limits and native module compilation.
Read moreSession Replay for Debugging: A Complete Guide
Learn how session replay works, when to use it, privacy considerations, and how it integrates with error tracking for faster debugging.
Read moreHow to Fix Referenceerror in .NET When Deploying
Learn how to diagnose and fix the referenceerror in .NET when deploying. Includes code examples and prevention tips.
Read moreHow to Fix Validationerror in TypeScript When Deploying
Learn how to diagnose and fix Validationerror errors in TypeScript when deploying. Step-by-step guide with code examples.
Read more