A memory leak is when an application keeps memory it no longer needs, so memory usage grows over time. Eventually this causes slow performance (more frequent and longer garbage collections), crashes with OutOfMemoryException, or container restarts. In unmanaged languages (C and C++), leaks happen when allocated memory is never freed. In .NET, the garbage collector frees unreachable objects automatically — so a .NET memory leak means objects are still reachable (referenced) even though the program will never use them again, or unmanaged resources are not released. Common causes in .NET 1. Event handlers not unsubscribed publisher.SomethingHappened += subscriber.Handle; A long-lived publisher keeps a reference to a short-lived subscriber, so the subscriber can never be collected. Unsubscribe (-=) or use weak events. 2. Static collections and caches that grow forever private static readonly List<Order> _processed = new(); // grows on every request Use bounded caches with size limits and expiration (MemoryCache with SizeLimit, or expiry policies). 3. Captured references Lambdas and closures capturing large objects that are stored in long-lived places (timers, static delegates, background tasks). 4. Timers not disposed System.Threading.Timer and similar objects keep callbacks alive. 5. Not disposing unmanaged resources Streams, database connections, HttpResponseMessage, native handles and images without using/Dispose — which also exhausts connection pools and handles. 6. Dependency injection mistakes Transient IDisposable services resolved from the root provider are tracked until application shutdown; scoped services captured by singletons. 7. Large object heap fragmentation and huge buffers held unnecessarily. 8. In UI frameworks: views kept alive by bindings or messengers; in web apps, storing large data in session or in-memory caches per user. How to detect leaks - Monitor memory over time (dotnet-counters, Application Insights or Prometheus metrics): a steadily rising baseline after garbage collections is the key signal. - Take memory snapshots or heap dumps at two points (dotnet-gcdump, dotnet-dump, Visual Studio diagnostic tools, JetBrains dotMemory, PerfView) and compare which object types keep growing, then inspect the paths to GC roots to find what keeps them alive. Prevention - Dispose resources with using; unsubscribe from events; bound caches; avoid static mutable state; review DI lifetimes; and run soak tests (long-running load tests) to catch slow leaks before production.
Ravindra Wadile · · 0 likes