Skip to content

[WiP] Fix leak on Command Element #26044

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

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion src/Controls/src/Core/CommandElement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,13 @@ public static void OnCommandChanged(BindableObject bo, object o, object n)
{
var commandElement = (ICommandElement)bo;
if (n is ICommand newCommand)
{
newCommand.CanExecuteChanged += commandElement.CanExecuteChanged;
commandElement.CanExecuteChanged(bo, EventArgs.Empty);

HandleTearDown(commandElement);

commandElement.CanExecuteChanged(bo, EventArgs.Empty);
}
}

public static void OnCommandParameterChanged(BindableObject bo, object o, object n)
Expand All @@ -35,5 +40,22 @@ public static bool GetCanExecute(ICommandElement commandElement)

return commandElement.Command.CanExecute(commandElement.CommandParameter);
}

static void HandleTearDown(ICommandElement commandElement)
{
if (commandElement is not VisualElement ve)
return;

ve.Unloaded -= OnUnloaded;
ve.Unloaded += OnUnloaded;
Comment on lines +49 to +50
Copy link
Contributor

Choose a reason for hiding this comment

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

What is the idea behind this?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

safe code to avoid the same control to subscribe the same event more than once. But this will be reworked, this approach will not be used


static void OnUnloaded(object? sender, EventArgs e)
{
if (sender is ICommandElement element && element.Command is not null)
{
element.Command.CanExecuteChanged -= element.CanExecuteChanged;
}
}
}
}
}
56 changes: 54 additions & 2 deletions src/Controls/tests/DeviceTests/Memory/MemoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Controls.Handlers;
Expand All @@ -29,18 +30,21 @@ void SetupBuilder()
handlers.AddHandler<ActivityIndicator, ActivityIndicatorHandler>();
handlers.AddHandler<Border, BorderHandler>();
handlers.AddHandler<BoxView, BoxViewHandler>();
handlers.AddHandler<Button, ButtonHandler>();

handlers.AddHandler<CarouselView, CarouselViewHandler>();
handlers.AddHandler<CollectionView, CollectionViewHandler>();
handlers.AddHandler<CheckBox, CheckBoxHandler>();
handlers.AddHandler<DatePicker, DatePickerHandler>();
handlers.AddHandler<Shape, ShapeViewHandler>();

handlers.AddHandler<Entry, EntryHandler>();
handlers.AddHandler<EntryCell, EntryCellRenderer>();
handlers.AddHandler<Editor, EditorHandler>();
#pragma warning disable CS0618 // Type or member is obsolete
handlers.AddHandler<Frame, FrameRenderer>();
#pragma warning restore CS0618 // Type or member is obsolete
handlers.AddHandler<GraphicsView, GraphicsViewHandler>();
handlers.AddHandler<Grid, LayoutHandler>();
handlers.AddHandler<HybridWebView, HybridWebViewHandler>();
handlers.AddHandler<Label, LabelHandler>();
handlers.AddHandler<ListView, ListViewRenderer>();
Expand All @@ -57,6 +61,7 @@ void SetupBuilder()
handlers.AddHandler<RefreshView, RefreshViewHandler>();
handlers.AddHandler<IScrollView, ScrollViewHandler>();
handlers.AddHandler<SearchBar, SearchBarHandler>();
handlers.AddHandler<Shape, ShapeViewHandler>();
handlers.AddHandler<Slider, SliderHandler>();
handlers.AddHandler<Stepper, StepperHandler>();
handlers.AddHandler<SwipeView, SwipeViewHandler>();
Expand Down Expand Up @@ -177,7 +182,7 @@ public async Task HandlerDoesNotLeak(Type type)
#if ANDROID
// NOTE: skip certain controls on older Android devices
if ((type == typeof(DatePicker) || type == typeof(ListView)) && !OperatingSystem.IsAndroidVersionAtLeast(30))
return;
return;

if (type == typeof(HybridWebView) && !OperatingSystem.IsAndroidVersionAtLeast(24))
{
Expand Down Expand Up @@ -559,6 +564,45 @@ await InvokeOnMainThreadAsync(() =>
}
#endif

[Fact("CommandElement, as Button, doesn't leak")]
public async Task DoesNotLeak()
{
SetupBuilder();

// Long-lived ICommand, like a Singleton ViewModel
var command = new MyCommand();
WeakReference reference = null;
var navPage = new NavigationPage(new ContentPage());
// Several GCs required on iOS

await CreateHandlerAndAddToWindow<WindowHandlerStub>(new Window(navPage), async window =>
{
var layout = new Grid();

var btn = new Button
{
Command = command
};

var label = new Label();
layout.Add(btn);

var page2 = new ContentPage
{
Content = layout
};

reference = new(btn);
await navPage.PushAsync(page2);
await OnLoadedAsync(btn);
await navPage.PopAsync();
await OnUnloadedAsync(page2);
});
Assert.NotNull(reference);

await AssertionExtensions.WaitForGC(reference);
}

[Fact]
public async Task TweenersWillNotLeakDuringInfiniteAnimation()
{
Expand Down Expand Up @@ -587,6 +631,14 @@ await CreateHandlerAndAddToWindow(new Window(page), async () =>
}
}

class MyCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter) => true;
public void Execute(object parameter) { }
public void FireCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}

sealed class AnimationPage : ContentPage
{
Button CounterBtn { get; } = new();
Expand Down
Loading