Memory leaks in .NET: the causes that kill your app (and how to avoid them)
Feeling like your app gets slower and slower in production? It might be a memory leak.
The garbage collector does most of the work, but it can't handle everything. Here are the causes I've run into on .NET projects.
1. No memory analysis during development
Without a profiler, you won't see the leaks. Simply use the Visual Studio memory profiler (Debug menu, Performance Profiler).
2. Unclosed files and connections (the classic)
Opening a file or DB connection without closing it = guaranteed leak. Always use using for anything that touches external resources.
True story: on one project, the app went down during traffic peaks. We checked the database: more than 1,000 open SQL connections.
3. A cache that grows forever
A cache without a duration or size limit = guaranteed problem. Always add a TimeToLive (MemoryCache.Set with AbsoluteExpiration).
4. Events without unsubscription
An event creates a reference that prevents memory collection. Never forget event -= MyHandler once you no longer need it.
5. Mishandled disposable objects
Objects using native resources (COM, handles, bitmaps...) escape the GC. Implement IDisposable and call GC.SuppressFinalize(this) in Dispose().
6. Static variables accumulating data
A static List<> that keeps filling = memory never released. Avoid storing large objects in static variables.
7. Objects referencing each other in a loop
A parent referencing a child referencing the parent = GC in agony. Use weak references (new WeakReference<MyType>(myObject)).
8. Long-lived collections that only grow
Lists stored in singletons or long-lived services end up keeping everything. Cap the collection size or clear them periodically.
9. Repeated operations on large arrays
Allocating a big array on every call = GC fatigue. Use ArrayPool<T> to reuse instead of recreating.
Takeaway: memory leaks are often invisible until your application slows down badly or crashes in production. Keep an eye on your apps' memory: if it climbs and never comes back down, one of these leaks may be the reason.
This article comes from one of my LinkedIn posts (in French): join the discussion ↗