Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[net7.0] fix memory leak in Window (#13400) #13654

Merged
merged 1 commit into from
Mar 3, 2023

Commits on Mar 2, 2023

  1. [controls] fix memory leak in Window (#13400)

    Fixes: #10029
    
    I could reproduce a memory leak by doing:
    
        App.Current.OpenWindow(new Window { Page = new ContentPage() });
    
    I found that `App.Current._requestedWindows` just held onto every
    `Window` object forever.
    
    Note that we *can't* use `ConditionalWeakTable` here:
    
    https://learn.microsoft.com/dotnet/api/system.runtime.compilerservices.conditionalweaktable-2
    
    After initially trying this, I added a test showing not to use it. The
    problem is if the `string` is GC'd the `Window` will be lost.
    
    We can use `Dictionary<string, WeakReference<Window>>` instead.
    
    The only other change I made was to use `Guid.ToString("n")` as it
    removes `{`, `}`, and `-` characters from the string.
    
    After these changes, I still found `Window` objects hanging around that
    appeared to be held onto by many other objects.
    
    Then I reviewed:
    
    ```csharp
    void IWindow.Destroying()
    {
        SendWindowDisppearing();
        Destroying?.Invoke(this, EventArgs.Empty);
        OnDestroying();
    
        Application?.RemoveWindow(this);
        // This wasn't here!
        Handler?.DisconnectHandler();
    }
    ```
    
    It appears that upon `Window`'s closing, we didn't have any code that
    "disconnected" the MAUI handler. After this change, I could see `Window`
    objects properly go away.
    
    I added a unit test as well.
    # Conflicts:
    #	src/Controls/tests/Core.UnitTests/WindowsTests.cs
    PureWeen committed Mar 2, 2023
    Configuration menu
    Copy the full SHA
    e6d3dbb View commit details
    Browse the repository at this point in the history