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() or OnDisappearing():
    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        myButton.Clicked -= OnClicked;
    }
  • Use using blocks to ensure IDisposable objects are released properly:
    using var stream = await file.OpenReadAsync();
  • Avoid unbounded static lists or dictionaries that retain references:
    static List<MyViewModel> cache = new(); // ❌ This list grows without limit
    Replace with weak references or clear the cache when no longer needed:
    cache.Clear();

πŸ“¦ Tools

Use dotnet-gcdump or Visual Studio’s Diagnostic Tools to inspect memory growth.

πŸ“š Additional Resources

➑️ Next: Optimize Image Usage

⚠️ **GitHub.com Fallback** ⚠️