Memory Leaks - davidortinau/ControlGallery GitHub Wiki
π¬ Copilot Chat Prompt
Help me identify potential memory leaks in my .NET MAUI app. Look for undisposed IDisposable objects, event handlers that aren't unsubscribed, and static collections that grow over time. Suggest how to fix or refactor them.
Memory leaks in .NET MAUI apps often come from lingering references in events, static caches, or undisposed objects.
π What to Look For
- Event handlers that are never unsubscribed
- Objects that implement
IDisposable
but are never disposed - Static lists or dictionaries that grow over time
π Common Fixes
- Always unsubscribe from events in
Dispose()
orOnDisappearing()
:protected override void OnDisappearing() { base.OnDisappearing(); myButton.Clicked -= OnClicked; }
- Use
using
blocks to ensureIDisposable
objects are released properly:using var stream = await file.OpenReadAsync();
- Avoid unbounded static lists or dictionaries that retain references:
Replace with weak references or clear the cache when no longer needed:static List<MyViewModel> cache = new(); // β This list grows without limit
cache.Clear();
π¦ Tools
Use dotnet-gcdump
or Visual Studioβs Diagnostic Tools to inspect memory growth.
π Additional Resources
- Memory leaks in .NET MAUI - GitHub Wiki
- dotnet-gcdump usage - Microsoft Docs
- IDisposable and finalizers
β‘οΈ Next: Optimize Image Usage