【问题标题】:Huge memory usage in XamarinXamarin 中的大量内存使用
【发布时间】:2017-08-08 15:45:45
【问题描述】:

我在一些旧的 Androiddevices 上运行我的应用程序时遇到了一些问题,因此我下载了 Visual Studio Professionel 的跟踪,因为它有 Diagnostics Tools

我尝试在我的应用程序中做一些简单的事情,但我发现这很吓人,Xamarin.Forms.BindableProperty+BindablePropertyContext 在 UWP 中的大小(当然以字节为单位)为 2.196.088,您可以在以下屏幕转储中看到。

.

在示例中,我刚刚浏览了 5 页。其中两页有ListViews,其中一页已被清空3次,并填充了新数据。

所以我必须在清除ListView 后拨打GC.Collect() 吗?

【问题讨论】:

  • 不建议调用GC.Collect(),因为它可能会破坏代码中的其他内容。 Clear() for ListView 不会在您的对象上调用 Dispose(),这意味着 GC 必须花时间确保在收集它们之前不会在其他任何地方引用这些对象。如果你愿意,你可以循环使用Dispose()ListView 中的每个项目,这将确保你销毁它们。看看这里。 stackoverflow.com/questions/1969024/…
  • @Everyone GC.Collect() 永远不会破坏任何其他东西,它只会让应用程序变慢,因为它是 CPU 密集型工作。
  • @AkashKava 真的,对不起。它会消耗性能,不会破坏正在运行的代码,但会大大减慢它的速度......就像很多

标签: c# android xamarin.android xamarin.forms


【解决方案1】:

我遇到过类似的问题 - 浏览页面几次导致 OutOfMemoryException。对我来说,解决方案是使用显式 Dispose() 调用实现页面的自定义渲染。

public class CustomPageRenderer : PageRenderer
{
    private NavigationPage _navigationPage;

    protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
    {
        base.OnElementChanged(e);
        _navigationPage = GetNavigationPage(Element);
        SubscribeToPopped(_navigationPage);
    }

    private void SubscribeToPopped(NavigationPage navigationPage)
    {
        if (navigationPage == null)
        {
            return;
        }

        navigationPage.Popped += OnPagePopped;
    }

    protected override void Dispose(bool disposing)
    {
        Log.Info("===========Dispose called===========");
        base.Dispose(disposing);
    }

    private void OnPagePopped(object sender, NavigationEventArgs args)
    {
        if (args.Page != Element)
        {
            return;
        }

        Dispose(true);
        _navigationPage.Popped -= OnPagePopped;
    }

    private static NavigationPage GetNavigationPage(Element element)
    {
        if (element == null)
        {
            return null;
        }

        while (true)
        {
            if (element.Parent == null || element.Parent.GetType() == typeof(NavigationPage))
            {
                return element.Parent as NavigationPage;
            }

            element = element.Parent;
        }
    }
}

你也可以看看here,但是你需要小心处理图片,如果他们的父页面在导航堆栈中并且你想返回,可能会导致一些问题。

【讨论】:

  • 谢谢@maddhew。我刚刚将 90-95% 的事件转换为命令,希望对您有所帮助。另外 5-10% 是我从构造函数转移到 OnAppearing 并在 OnDisappearing 中取消分配。而且我已将所有图像转换为 9 补丁(在 Android 上)。我希望它会采取一些它。
猜你喜欢
  • 2018-02-21
  • 2018-04-18
  • 2014-04-02
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
  • 2012-01-13
  • 2023-03-24
  • 1970-01-01
相关资源
最近更新 更多