【问题标题】:Memory leak handling Xamarin.Forms内存泄漏处理 Xamarin.Forms
【发布时间】:2015-06-14 07:58:18
【问题描述】:

我使用 Xamarin.Forms 创建的应用程序中存在内存泄漏问题。我的应用由带有图像的 ListView 组成。如果我单击一个项目并返回到 ListPage,我可以在我的输出窗口中看到一个内存占用。我尝试在我的 ContentPage 的 OnDisappearing() 中调用 GC.Collect()

我在我的 Android 项目中看到了 base.Dispose()。但是我不知道怎么用。

ArticleListPage.xaml

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:converters="clr-namespace:NewsArticles.Mobile.Converters;assembly=Something.NewsArticles.Mobile"
             xmlns:themes="clr-namespace:NewsArticles.Mobile.Themes;assembly=Something.NewsArticles.Mobile"
             x:Class="NewsArticles.Mobile.Pages.ArticlesListPage"
             Title="{Binding PageTitle, Mode=OneWay}"
             BackgroundColor="{x:Static themes:ColorResources.ArticleListPageBackgroundColor}">
  <RelativeLayout>
    <ContentPage.Resources>
      <ResourceDictionary>
        <converters:BooleanNegationConverter x:Key="booleanNegationConverter" />
        <converters:StringToImageSourceConverter x:Key="stringToImageSourceConverter" />
      </ResourceDictionary>
    </ContentPage.Resources>



      <ListView x:Name="ArticlesList"
                StyleId="ArticlesList"
                      Grid.Row="1"
                      IsVisible="{Binding IsProcessing, Mode=OneWay, Converter={StaticResource booleanNegationConverter}}">
        <ListView.BackgroundColor>
          <OnPlatform x:TypeArguments="Color" iOS="Transparent" />
        </ListView.BackgroundColor>
        <ListView.RowHeight>
          <OnPlatform x:TypeArguments="x:Int32" iOS="150" Android="180" WinPhone="170" />
        </ListView.RowHeight>
        <ListView.ItemTemplate>
          <DataTemplate>
            <ViewCell>
              <ContentView BackgroundColor="{x:Static themes:ColorResources.ArticleListViewBackgroundColor}">
                <ContentView.Padding>
                  <OnPlatform x:TypeArguments="Thickness"
                     iOS="10,5"
                     Android="10,10"
                     WinPhone="10,10" />
                </ContentView.Padding>

                <Grid BackgroundColor="White" Padding="10">
                  <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="120"/>
                    <ColumnDefinition Width="*" />
                  </Grid.ColumnDefinitions>

                  <Image Grid.Column="0"
                         Source="{Binding ImageUrl, Mode=OneWay, Converter={StaticResource stringToImageSourceConverter}}"
                         HorizontalOptions="FillAndExpand"
                         Aspect="AspectFill" />

                  <Grid Grid.Column="1" RowSpacing="0">
                    <Grid.RowDefinitions>
                      <RowDefinition Height="Auto" />
                      <RowDefinition Height="20" />
                      <RowDefinition Height="*" />
                    </Grid.RowDefinitions>
                    <Label Grid.Row="0" Text="{Binding Title, Mode=OneWay}"
                           VerticalOptions="Start"
                           LineBreakMode="WordWrap"
                           TextColor="{x:Static themes:ColorResources.MainArticleTitleColor}"
                           Font="{x:Static themes:FontResources.ListArticleTitle}" />

                    <ContentView Grid.Row="1" Padding="0,2">
                      <Label Text="{Binding Author, Mode=OneWay }"
                             TextColor="Silver"
                             Font="{x:Static themes:FontResources.VerySmall}" />
                    </ContentView>

                    <Label Grid.Row="2" Text="{Binding Body, Mode=OneWay}"
                         LineBreakMode="TailTruncation"
                         TextColor="Gray"
                         Font="{x:Static themes:FontResources.VerySmall}" />
                  </Grid>
                </Grid>
              </ContentView>

            </ViewCell>
          </DataTemplate>
        </ListView.ItemTemplate>
      </ListView>
</ContentPage>

【问题讨论】:

  • 如何加载图像?它是纯粹的 Forms 应用程序,还是您在 Droid 项目中做事?
  • 另外,您是使用 XAML 还是仅使用代码隐藏?
  • @fredrik 它是一个纯表单项目。我正在使用 Xaml 进行设计。我的 Android 项目中几乎没有任何代码。我想知道我是否可以编写自定义渲染器
  • 不久前我遇到了这个确切的问题。然后我找到了this。这似乎与此重复,我将建议将其关闭。如果这不能解决问题 - 提交重新打开文件或发布包含更多信息的新问题。
  • @fredrik 感谢您的回复。我已经写了渲染器。如何从我的 ContentPage 类访问它?

标签: c# android memory-leaks xamarin.forms


【解决方案1】:

不久前我遇到了这个问题,this 文章为我解决了这个问题。 基本上,您需要制作一个自定义渲染器并将其放置在您的 droid 项目中:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Views.InputMethods;
using Android.Widget;
using Android.Util;
using Application.Droid.CustomControls;
using ApplicationClient.CustomControls;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

    [assembly: ExportRenderer(typeof(ApplicationClient.CustomControls.LSImage), typeof(LSImageRenderer))]

    namespace Application.Droid.CustomControls
    {
        public class LSImageRenderer : ImageRenderer
        {
            Page page;
            NavigationPage navigPage;

            protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
            {
                base.OnElementChanged(e);
                if (e.OldElement == null)
                {
                    if (GetContainingViewCell(e.NewElement) != null)
                    {
                        page = GetContainingPage(e.NewElement);
                        if (page.Parent is TabbedPage)
                        {
                            page.Disappearing += PageContainedInTabbedPageDisapearing;
                            return;
                        }

                        navigPage = GetContainingNavigationPage(page);
                        if (navigPage != null)
                            navigPage.Popped += OnPagePopped;
                    }
                    else if ((page = GetContainingTabbedPage(e.NewElement)) != null)
                    {
                        page.Disappearing += PageContainedInTabbedPageDisapearing;
                    }
                }
            }

            void PageContainedInTabbedPageDisapearing (object sender, EventArgs e)
            {
                this.Dispose(true);
                page.Disappearing -= PageContainedInTabbedPageDisapearing;
            }

            protected override void Dispose(bool disposing)
            {
                Log.Info("**** LSImageRenderer *****", "Image got disposed");
                base.Dispose(disposing);
            }

            private void OnPagePopped(object s, NavigationEventArgs e)
            {
                if (e.Page == page)
                {
                    this.Dispose(true);
                    navigPage.Popped -= OnPagePopped;
                }
            }

            private Page GetContainingPage(Xamarin.Forms.Element element)
            {
                Element parentElement = element.ParentView;

                if (typeof(Page).IsAssignableFrom(parentElement.GetType()))
                    return (Page)parentElement;
                else
                    return GetContainingPage(parentElement);
            }

            private ViewCell GetContainingViewCell(Xamarin.Forms.Element element)
            {
                Element parentElement = element.Parent;

                if (parentElement == null)
                    return null;

                if (typeof(ViewCell).IsAssignableFrom(parentElement.GetType()))
                    return (ViewCell)parentElement;
                else
                    return GetContainingViewCell(parentElement);
            }

            private TabbedPage GetContainingTabbedPage(Element element)
            {
                Element parentElement = element.Parent;

                if (parentElement == null)
                    return null;

                if (typeof(TabbedPage).IsAssignableFrom(parentElement.GetType()))
                    return (TabbedPage)parentElement;
                else
                    return GetContainingTabbedPage(parentElement);
            }

            private NavigationPage GetContainingNavigationPage(Element element)
            {
                Element parentElement = element.Parent;

                if (parentElement == null)
                    return null;

                if (typeof(NavigationPage).IsAssignableFrom(parentElement.GetType()))
                    return (NavigationPage)parentElement;
                else
                    return GetContainingNavigationPage(parentElement);
            }
        }
    }

然后扩展 Image 类并将其放置在 PCL 中,或者您的页面所在的任何位置。

namespace ApplicationClient.CustomControls
{
    public class LSImage : Image
    {
    }
}

那么您必须修改 XAML 才能使用它。

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:ctrls="clr-namespace:ApplicationClient.CustomControls;assembly=ApplicationClient"
             ... >
  <ctrls:LSImage ... />
</ContentPage>

【讨论】:

  • 你能帮我处理 MasterDetailPage Tweeks 吗?
  • 即使我如上所述使用 LsImage,主详细信息页面中的图像也没有得到处理。就像如果我重复打开一个包含图像的弹出窗口 5 次我可以看到内存急剧增加,我们该如何处理它
  • @george-thomas 这在最近的版本中已经停止工作,或者没有触发垃圾收集器。此外,在没有看到更多代码的情况下,我不能排除您保留对阻止垃圾收集器释放内存的内容的引用。
  • @fredrik 我对表单应用程序完全陌生,我在弹出窗口中使用的代码在这里stackoverflow.com/questions/43862505/…
  • @GeorgeThomas 似乎没有保留任何引用,但仍有可能是垃圾收集器尚未为您运行。
猜你喜欢
  • 2021-01-14
  • 2017-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-07
相关资源
最近更新 更多