My app navigates using the following shell command:
await Shell.Current.GoToAsync("PageName");
I've been experiencing performance issues which become worse the longer you use the app so I figured I might not be releasing resources. On further investigation I discovered that every page I've navigated to remains active in memory and never disposed of. If a page contains a timer then that timer continues to run long after I've navigated away from the page.
I need to find a very basic means of navigation where there is only ever one page active at any one time and the last page is always disposed of when I navigate to the next page. I never need a previous page to remain alive.
Does anyone know how this can be achieved please?
When using Shell navigation, I expected the previous page to be disposed of. Tests show this isn't the case.
Thanks!
Thanks so much for your help guys. This solution works great!
You always get the same instance of each requested page. No more nasty page build up in memory. Just make sure any timers are instantiated in the constructor and turned on/off in the Disappearing/Appearing events or disposed of properly in the Disappearing event as they will live on and build up in the background if not handled properly.
public partial class App : Application
{
public static IServiceProvider Services;
public App(IServiceProvider services)
{
Services = services;
InitializeComponent();
MainPage = App.Services.GetService<InitialPage>();
}
}
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.UseMauiCommunityToolkit()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
});
// Cache Pages
builder.Services.AddSingleton<InitialPage>();
builder.Services.AddSingleton<Page1>();
builder.Services.AddSingleton<Page2>();
builder.Services.AddSingleton<Page3>();
return builder.Build();
}
}
Application.Current.MainPage = App.Services.GetService<Page1>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With