在Xamarin.Forms的NavigationPage上推送大量页面所使用的内存 [英] Memory used by pushing a lot of pages on Xamarin.Forms' NavigationPage

查看:132
本文介绍了在Xamarin.Forms的NavigationPage上推送大量页面所使用的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Xamarin.Forms NavigationPage,我注意到在推送了很多页面(例如20个)之后,该应用程序开始变得迟钝,并可能在某些时候冻结.我猜想它一定要占用很多内存(考虑到我现在应该真正检查Android的监视工具).

I have a Xamarin.Forms NavigationPage and I noticed that after pushing quite a lot of pages (say 20), the app starts being laggy and might freeze at some point. I'm guessing it must be using a lot of memory (I should really check in Android's monitoring tools now that I thought about it).

还有另一种方式可以提供不会耗尽所有内存的历史记录功能(因此,用户可以随时按回去他们以前阅读的位置)吗?我知道这是有可能的,因为它是在其他应用程序中完成的.

Is there another way I can provide a history functionality (so, the user can always press back to go to where they were reading before) that doesn't eat up all the memory? I know it's possible because it's done in other apps.

推荐答案

对于具有多个页面和较大导航堆栈的解决方案,您可以使用PagesFactory:

For solutions with multiple pages and large navigation stack You could use PagesFactory:

public static class PagesFactory
{
    static readonly Dictionary<Type, Page> pages = new Dictionary<Type, Page>();

    static NavigationPage navigation;
    public static NavigationPage GetNavigation()
    {
        if (navigation == null)
        {
            navigation = new NavigationPage(PagesFactory.GetPage<Views.MainMenuView>());
        }
        return navigation;
    }

    public static T GetPage<T>(bool cachePages = true) where T : Page
    {
        Type pageType = typeof(T);

        if (cachePages)
        {
            if (!pages.ContainsKey(pageType))
            {
                Page page = (Page)Activator.CreateInstance(pageType);
                pages.Add(pageType, page);
            }

            return pages[pageType] as T;
        }
        else
        {
            return Activator.CreateInstance(pageType) as T;
        }
    }

    public static async Task PushAsync<T>() where T : Page
    {
        await GetNavigation().PushAsync(GetPage<T>());
    }

    public static async Task PopAsync()
    {
        await GetNavigation().PopAsync();
    }

    public static async Task PopToRootAsync()
    {
        await GetNavigation().PopToRootAsync();
    }

    public static async Task PopThenPushAsync<T>() where T : Page
    {
        await GetNavigation().PopAsync();
        await GetNavigation().PushAsync(GetPage<T>());
    }
}

这篇关于在Xamarin.Forms的NavigationPage上推送大量页面所使用的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆