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

Fix memory leak in VisualElement.Shadow #13960

Merged
merged 8 commits into from
Mar 21, 2023
Merged

Conversation

jsuarezruiz
Copy link
Contributor

@jsuarezruiz jsuarezruiz commented Mar 15, 2023

Description of Change

This is very much to 58a42e5 and 61fbb00

I used the same technique in 58a42e5, and added a unit test to validate the changes.

NOTE: It's a Draft until we review how to properly propagate the Parent to the Shadow (and others).

@jsuarezruiz jsuarezruiz added t/bug Something isn't working legacy-area-perf Startup / Runtime performance labels Mar 15, 2023
/// General usage is to store this in a member variable and call Subscribe()/Unsubscribe() appropriately.
/// Your class should have a finalizer that calls Unsubscribe() to prevent WeakNotifyCollectionChangedProxy objects from leaking.
/// </summary>
class WeakNotifyPropertyChangedProxy : WeakEventProxy<INotifyPropertyChanged, PropertyChangedEventHandler>
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a generic proxy to manage the PropertyChanged event.

Copy link
Member

@jonathanpeppers jonathanpeppers left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR looks correct, if the tests pass.

So the only outstanding issue is what to do about Parent. I don't know if we need to solve that before merging?

@jonathanpeppers
Copy link
Member

jonathanpeppers commented Mar 15, 2023

@mandel-macaque the reason to make a local here is in case two threads are in here at once.

@mandel-macaque
Copy link
Member

mandel-macaque commented Mar 16, 2023

@mandel-macaque the reason to make a local here is in case two threads are in here at once.

@jonathanpeppers That is valid point in a multithreaded case, BUT in that case the assignment would be an issue since the ??= operator will be expanded to a if (f != null) f = new(); Therefore we have two possible cases:

  1. We are only in the UI thread and there is not need for the local variable.
  2. We are in a multithreaded environment and then the ??= is dangerous because there can be two threads trying to assign the _shadowProxy variable.

Regarding point 2: https://sharplab.io/#v2:CYLg1APgAgTAjAWAFDKgZgASwwdQJYB2wA9gO4YgYCSAIngM4AOx9AhgEYA2AphgN7IMQjIOHosAFgx0mLXgAoAlP1HDhAenUZ6AW1YAnAC4ZDAC0IBzehlOtGjbgVUYAvs+fiocAGy5CJUgB+DABhfW5WQwVlASQ1NSgAdgxgbgAzVgBXTkMAbmc3FCRC1BhMWLUPHwxidgArbgBjQ2CAfSj6YwBeDAJszny4sUwvX1qG5owAFW5OjCUVIfiMdtnjQMCegm5ycabDJUHloSSVjryC9yWRYqA===

You can see how a ??= is the following:

public static class Program
{
    [System.Runtime.CompilerServices.Nullable(2)]
    private static object _test;

    [System.Runtime.CompilerServices.NullableContext(1)]
    public static object Test()
    {
        if (_test == null)
        {
            _test = new object();
        }
        return _test;
    }
}

Two threads can be creating two diff _shadowObjets. So either for 1 or 2 the code is not correct.

@mandel-macaque
Copy link
Member

mandel-macaque commented Mar 16, 2023

@jonathanpeppers @jsuarezruiz for reference: dotnet/docs#27613 BUT the using null conditional operators IS thread safe (the joys of the documentation): Null-conditional operators ?. and ?[]

So be careful, some are thread-safe, but not all are thread-safe. Example:

static object? _test = null;
    public static object Test () {
        _test ??= new object();
        _test?.ToString ();
        return _test;
    }

Generated:

[System.Runtime.CompilerServices.NullableContext(1)]
    public static object Test()
    {
        if (_test == null)
        {
            _test = new object();
        }
        object test = _test;
        if (test != null)
        {
            test.ToString();
        }
        return _test;
    }

Comment on lines 311 to 314
if (shadow is not null)
{
Shadow.Parent = this;
Shadow.PropertyChanged += OnShadowChanged;
var proxy = _shadowProxy ??= new();
proxy.Subscribe(shadow, (sender, e) => OnPropertyChanged(nameof(Shadow)));
Copy link
Member

@jonathanpeppers jonathanpeppers Mar 16, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As seen in: #13997

I think you can change this to:

_shadowHandler ??= (sender, e) => OnPropertyChanged(nameof(Shadow));
_shadowProxy ??= new();
proxy.Subscribe(shadow, _shadowHandler);

Where _shadowHandler is a member field to hold onto the EventHandler and make this test pass: https://github.com/dotnet/maui/pull/13960/files#r1139276236

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, just so that people get why we need the extra local var, we are not trying to fix a thread race condition, but a memory race condition in which the GC kicks ins that is why the code is confusing. There are not thread race conditions because everything should be happening in the main/ui thread. Is just that the fix is to use a local var to keep the ref until we don't longer need it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, the test was not passing in that case.
Applied changes to save the EventHandlers in a member field.
image

Copy link
Member

@jonathanpeppers jonathanpeppers left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good now, hopefully CI is green. 👍

@jsuarezruiz jsuarezruiz marked this pull request as ready for review March 20, 2023 08:09
@rmarinho rmarinho merged commit c54d3a6 into main Mar 21, 2023
@rmarinho rmarinho deleted the housekeeping-shadow-leak branch March 21, 2023 10:58
@github-actions github-actions bot locked and limited conversation to collaborators Dec 13, 2023
@Eilon Eilon added t/perf The issue affects performance (runtime speed, memory usage, startup time, etc.) area-controls-general General issues that span multiple controls, or common base classes such as View or Element labels May 10, 2024
@samhouts samhouts added the fixed-in-8.0.0-preview.3.8149 Look for this fix in 8.0.0-preview.3.8149! label Aug 2, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area-controls-general General issues that span multiple controls, or common base classes such as View or Element fixed-in-8.0.0-preview.3.8149 Look for this fix in 8.0.0-preview.3.8149! legacy-area-perf Startup / Runtime performance t/bug Something isn't working t/perf The issue affects performance (runtime speed, memory usage, startup time, etc.)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

6 participants