Skip to content
12 changes: 1 addition & 11 deletions src/Controls/samples/Controls.Sample.Sandbox/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,6 @@ public App()

protected override Window CreateWindow(IActivationState? activationState)
{
// To test shell scenarios, change this to true
bool useShell = false;

if (!useShell)
{
return new Window(new NavigationPage(new MainPage()));
}
else
{
return new Window(new SandboxShell());
}
return new Window(new AppFlyoutPage());
}
}
23 changes: 23 additions & 0 deletions src/Controls/samples/Controls.Sample.Sandbox/AppFlyoutPage.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8" ?>
<FlyoutPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Maui.Controls.Sample.AppFlyoutPage"
Title="AppFlyoutPage">
<FlyoutPage.Flyout>
<ContentPage Title="Menu">
<CollectionView ItemsSource="{Binding MenuItems}"
SelectionMode="Single"
SelectionChanged="OnMenuItemSelected">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="10">
<Label Text="{Binding Title}"
FontSize="16"
VerticalOptions="Center"/>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</ContentPage>
</FlyoutPage.Flyout>
</FlyoutPage>
42 changes: 42 additions & 0 deletions src/Controls/samples/Controls.Sample.Sandbox/AppFlyoutPage.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using Maui.Controls.Sample.Services;

namespace Maui.Controls.Sample;

public partial class AppFlyoutPage : FlyoutPage
{
public class MenuItem
{
public string Title { get; set; } = string.Empty;
public Type PageType { get; set; } = typeof(Page);
}

public List<MenuItem> MenuItems { get; set; }

public AppFlyoutPage()
{
InitializeComponent();

MenuItems = new List<MenuItem>
{
new MenuItem { Title = "page 1", PageType = typeof(Page1) },
new MenuItem { Title = "page 2", PageType = typeof(Page2) }
};

BindingContext = this;

// Set default detail page
Detail = new NavigationPage(new Page1());
}

private void OnMenuItemSelected(object? sender, SelectionChangedEventArgs e)
{
if (e.CurrentSelection.FirstOrDefault() is MenuItem selectedItem)
{
var navigationService = new NavigationService();
navigationService.Navigate(selectedItem.PageType);

// Close the flyout after selection
IsPresented = false;
}
}
}
19 changes: 19 additions & 0 deletions src/Controls/samples/Controls.Sample.Sandbox/Page1.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Maui.Controls.Sample.Page1"
Title="page 1">
<VerticalStackLayout Padding="30"
Spacing="25"
VerticalOptions="Center"
HorizontalOptions="Center">
<Button Text="page 1"
Clicked="OnNavigateToPage2Clicked"
HorizontalOptions="Center"/>
<Button Text="Navigate to Page 2"
Clicked="OnNavigateToPage2AsyncClicked"
HorizontalOptions="Center"/>

<Entry Text="Test"/>
</VerticalStackLayout>
</ContentPage>
29 changes: 29 additions & 0 deletions src/Controls/samples/Controls.Sample.Sandbox/Page1.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using Maui.Controls.Sample.Services;

namespace Maui.Controls.Sample;

public partial class Page1 : ContentPage
{
private readonly NavigationService _navigationService;

public Page1()
{
InitializeComponent();
_navigationService = new NavigationService();

Loaded += (e, __) =>
{
_ = MemoryTest.IsAliveAsync();
};
}

private void OnNavigateToPage2Clicked(object? sender, EventArgs e)
{
_navigationService.NavigateAbsolute(typeof(Page2));
}

private void OnNavigateToPage2AsyncClicked(object? sender, EventArgs e)
{
_navigationService.Navigate(typeof(Page2));
}
}
18 changes: 18 additions & 0 deletions src/Controls/samples/Controls.Sample.Sandbox/Page2.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Maui.Controls.Sample.Page2"
Title="page 2">
<VerticalStackLayout Padding="30"
Spacing="25"
VerticalOptions="Center"
HorizontalOptions="Center">
<Label Text="page 2"
FontSize="32"
HorizontalOptions="Center"/>
<Button Text="Navigate to Page 1"
Clicked="OnNavigateToPage1Clicked"
HorizontalOptions="Center"/>
<Entry Text="Test"/>
</VerticalStackLayout>
</ContentPage>
19 changes: 19 additions & 0 deletions src/Controls/samples/Controls.Sample.Sandbox/Page2.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using Maui.Controls.Sample.Services;

namespace Maui.Controls.Sample;

public partial class Page2 : ContentPage
{
private readonly NavigationService _navigationService;

public Page2()
{
InitializeComponent();
_navigationService = new NavigationService();
}

private void OnNavigateToPage1Clicked(object? sender, EventArgs e)
{
_navigationService.Navigate(typeof(Page1));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
namespace Maui.Controls.Sample.Services;

public class NavigationService
{
public void NavigateAbsolute(Type pageType)
{
var flyoutPage = new AppFlyoutPage();

if (pageType == typeof(Page1))
{
flyoutPage.Detail = new NavigationPage(new Page1());
}
else if (pageType == typeof(Page2))
{
flyoutPage.Detail = new NavigationPage(new Page2());
}

var page = (flyoutPage.Detail as NavigationPage)!.CurrentPage;

MemoryTest.Add(flyoutPage);
MemoryTest.Add(flyoutPage.Detail);
MemoryTest.Add(page);
Application.Current!.Windows[0].Page = flyoutPage;
}

public void Navigate(Type pageType)
{
var currentPage = Application.Current!.Windows[0].Page;

if (currentPage is FlyoutPage flyoutPage && flyoutPage.Detail is NavigationPage navigationPage)
{
Page? targetPage = null;

if (pageType == typeof(Page1))
{
targetPage = new Page1();
}
else if (pageType == typeof(Page2))
{
targetPage = new Page2();
}

if (targetPage != null)
{
flyoutPage.Detail = new NavigationPage(targetPage);
flyoutPage.IsPresented = false;
}


MemoryTest.Add(flyoutPage);
MemoryTest.Add(flyoutPage.Detail);
MemoryTest.Add(targetPage!);
}
}
}
static class MemoryTest
{
static readonly List<WeakReference<object>> weakReferences = [];

public static int Count => weakReferences.Count;

public static void Add(object obj)
{
weakReferences.Add(new(obj));
}

public static async Task IsAliveAsync()
{
RunGC();
for (var i = 0; i < weakReferences.Count; i++)
{
var item = weakReferences[i];

if (item.TryGetTarget(out var target))
{
var type = target.GetType();
var name = type.FullName;

#pragma warning disable CS0618 // Type or member is obsolete
await App.Current!.MainPage!.DisplayAlert("Memory leak!", $"The {name} object of {type} Type is still alive", "Ok");
#pragma warning restore CS0618 // Type or member is obsolete
}
else
{
weakReferences.Remove(item);
}
RunGC();
}


#pragma warning disable CS0618 // Type or member is obsolete
await App.Current!.MainPage!.DisplayAlert("Memory leak!", $"The are {weakReferences.Count} objects still alive", "Ok");
#pragma warning restore CS0618 // Type or member is obsolete
}

static void RunGC()
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
1 change: 1 addition & 0 deletions src/Controls/src/Core/FlyoutPage/FlyoutPage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ public Page Detail
{
previousDetail.SendNavigatedFrom(
new NavigatedFromEventArgs(destinationPage: value, NavigationType.Replace));
previousDetail.Handler?.DisconnectHandler();
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not 100% sure about this one, maybe the dev. should be responsible to call the DisconnectHandler?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think this is fine but we would want to call DisconnectHAndler after the page is unloaded

if you look at "void OnPageChanged(Page? oldPage, Page? newPage)" inside window you'll see where I wire into the unloaded event and then call disocnnecthandler from there.

Copy link
Copy Markdown
Contributor Author

@pictos pictos Jan 2, 2026

Choose a reason for hiding this comment

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

it will not work, that method isn't called when the FyoutPage.Detail is replaced. For reference this is the scenario that opened the issue

https://github.com/3sRykaert/MauiMemoryleak/blob/5aced80e41a6a70b17b58b5a93054207150a4d05/MauiMemoryleak/NavigationService.cs#L18-L31

}

_detail.SendNavigatedTo(new NavigatedToEventArgs(previousDetail, NavigationType.Replace));
Expand Down
86 changes: 86 additions & 0 deletions src/Controls/tests/DeviceTests/Memory/MemoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ void SetupBuilder()
handlers.AddHandler<TimePicker, TimePickerHandler>();
handlers.AddHandler<Toolbar, ToolbarHandler>();
handlers.AddHandler<WebView, WebViewHandler>();
handlers.AddHandler<FlyoutPage, FlyoutViewHandler>();

#if IOS || MACCATALYST
handlers.AddHandler<NavigationPage, NavigationRenderer>();
Expand Down Expand Up @@ -577,6 +578,91 @@ await CreateHandlerAndAddToWindow(window, async () =>
await AssertionExtensions.WaitForGC([.. references]);
}

[Fact("FlyoutPage Detail Handler Is Disconnected When Replaced")]
public async Task FlyoutPageDetailDoesNotLeak()
{
SetupBuilder();

var references = new List<WeakReference>();
var flyoutPage = new FlyoutPage
{
Flyout = new ContentPage { Title = "Flyout" },
Detail = new NavigationPage(new ContentPage { Title = "Initial Detail" })
};

await CreateHandlerAndAddToWindow(new Window(flyoutPage), async () =>
{
await OnLoadedAsync(flyoutPage);

// Capture old detail and its handler before replacement
var oldDetail = flyoutPage.Detail;
var oldHandler = oldDetail.Handler;
Assert.NotNull(oldHandler);

references.Add(new(oldDetail));
references.Add(new(oldHandler));
references.Add(new(oldHandler.PlatformView));

// Replace detail
var newDetailPage = new ContentPage { Title = "New Detail" };
flyoutPage.Detail = new NavigationPage(newDetailPage);
await OnLoadedAsync(newDetailPage);

// The fix calls previousDetail.Handler?.DisconnectHandler() in the Detail setter.
// Without the fix, the old handler stays connected (non-null).
Assert.Null(oldDetail.Handler);

oldDetail = null;
oldHandler = null;
});

await AssertionExtensions.WaitForGC([.. references]);
}

[Fact("FlyoutPage Detail Handler Disconnects With Multiple Replacements")]
public async Task FlyoutPageDetailDoesNotLeakWithMultipleReplacements()
{
SetupBuilder();

var references = new List<WeakReference>();
var flyoutPage = new FlyoutPage
{
Flyout = new ContentPage { Title = "Flyout" },
Detail = new NavigationPage(new ContentPage { Title = "Initial Detail" })
};

await CreateHandlerAndAddToWindow(new Window(flyoutPage), async () =>
{
await OnLoadedAsync(flyoutPage);

for (int i = 0; i < 5; i++)
{
var oldDetail = flyoutPage.Detail;
var oldHandler = oldDetail.Handler;
Assert.NotNull(oldHandler);

if (i < 3)
{
references.Add(new(oldDetail));
references.Add(new(oldHandler));
references.Add(new(oldHandler.PlatformView));
}

Copy link

Copilot AI Jan 3, 2026

Choose a reason for hiding this comment

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

The test delays (Task.Delay(50)) appear to be used to allow async operations to complete, but this could make tests flaky. Consider using a more deterministic approach, such as waiting for specific conditions or events to complete. If the delays are necessary for the GC to run or for fragments to be destroyed, add a comment explaining why this specific delay is needed.

Suggested change
// Give the platform time to complete disposal/teardown of the previous Detail
// (handlers, native views, fragments) before proceeding to the next iteration.
// This small delay has been found necessary to make the subsequent GC-based
// memory assertions reliable across devices.

Copilot uses AI. Check for mistakes.
var newDetailPage = new ContentPage { Title = $"Detail {i}" };
flyoutPage.Detail = new NavigationPage(newDetailPage);
await OnLoadedAsync(newDetailPage);

// Each replacement must disconnect the previous detail's handler
Assert.Null(oldDetail.Handler);

oldDetail = null;
oldHandler = null;
}
});

await AssertionExtensions.WaitForGC([.. references]);
}

[Fact("VisualDiagnosticsOverlay Does Not Leak"
#if IOS || MACCATALYST
, Skip = "Fails with 'MauiContext should have been set on parent.'"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,11 @@ public MauiNavHostFragment()
protected MauiNavHostFragment(nint javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}

public override void OnDestroy()
{
base.OnDestroy();
this.Dispose();
Copy link

Copilot AI Jan 2, 2026

Choose a reason for hiding this comment

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

Calling Dispose() on a Fragment is unnecessary and potentially problematic. Android's Fragment lifecycle already handles resource cleanup through OnDestroy(). Explicitly calling Dispose() can cause issues with the Fragment lifecycle and may lead to double-disposal or premature resource cleanup.

Suggested change
this.Dispose();

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

not calling the dispose causes the memory leak

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hmmm this seems wrong though, we shouldn't need to call Dispose here to fix a memory leak.
This seems like maybe the dispose is triggering something else that's possibilty fixing the leak?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@PureWeen not sure... Maybe it's somehow removing it from the fragmentManager? The leaks on android specific code was related to bad clean up on FragmentManager, before trying to call dispose I did all I find to remove the navHost from the fragment manager but nothing helped. Maybe calling the dispose from StackNavigationManager would be better?

}
}
}
Loading
Loading