Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prior pages are still active and never disposed

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!

like image 344
Sutts99 Avatar asked Sep 15 '25 13:09

Sutts99


1 Answers

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.


App.xaml.cs

public partial class App : Application
{
    public static IServiceProvider Services;

    public App(IServiceProvider services)
    {
        Services = services;

        InitializeComponent();

        MainPage = App.Services.GetService<InitialPage>();
    }
}

MauiProgram.cs

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();
    }
}

ContentPage Code To Switch Page

Application.Current.MainPage = App.Services.GetService<Page1>();
like image 178
Sutts99 Avatar answered Sep 18 '25 09:09

Sutts99