You need to enable JavaScript to run this app. Xamarin.Forms ListView用RecycleElement频繁触发GC致应用卡顿问题
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin.Forms ListView用RecycleElement频繁触发GC致应用卡顿问题

Xamarin.Forms ListView配置RecycleElement后内存泄漏、构造持续调用问题排查

核心问题现象

  • 已为ListView设置CachingStrategy="RecycleElement",ItemTemplate中嵌入基于Lottie实现的自定义复选框控件CheckboxLottie
  • 异常表现:自定义控件构造方法被持续触发,即便导航移除承载该ListView的页面,相关对象仍未被垃圾回收,伴随频繁GC日志输出、应用运行卡顿
  • 对照验证:将ViewCell替换为仅包含绑定属性的简单Label实现,同样出现构造持续调用、频繁触发GC的问题,初步排除自定义Lottie控件的逻辑作为根因

相关实现代码

自定义Lottie复选框

public class CheckboxLottie : AnimationView
{
    public static BindableProperty IsCheckedProperty = BindableProperty.Create(
        nameof(IsChecked), 
        typeof(bool), 
        typeof(CheckboxLottie), 
        defaultBindingMode: BindingMode.TwoWay, 
        propertyChanged: IsCheckedChanged);

    public bool IsChecked
    {
        get { return (bool)GetValue(IsCheckedProperty); }
        set { SetValue(IsCheckedProperty, value); }
    }

    static void IsCheckedChanged(BindableObject bindable, object oldValue, object newValue)
    {
        if (!(bindable is CheckboxLottie cb))
            return;

        if ((bool)newValue)
        {
            cb.PlayMinAndMaxProgress(0.98f, 0.99f);
        }
        else
        {
            cb.PlayMinAndMaxProgress(0.0f, 0.015f);
        }
    }

    public CheckboxLottie()
    {
        Animation = "checkbox.json";
        AutoPlay = false;
        Clicked += Checkbox_OnClick;
    }

    void Checkbox_OnClick(object sender, EventArgs e)
    {
        IsChecked = !IsChecked;
    }
}

页面XAML实现

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:models="clr-namespace:MyApp.Model"
             xmlns:controls="clr-namespace:MyApp.Controls" 
             mc:Ignorable="d"
             x:Class="MyApp.Views.ListPage">
    <ContentPage.Resources>
        <DataTemplate x:Key="toolTipTemplate2"  x:DataType="models:MyItem">
            <ViewCell>
                <controls:CheckboxLottie IsChecked="{Binding checkboxChecked}"/>
            </ViewCell>
        </DataTemplate>
    </ContentPage.Resources>
    
    <ContentPage.Content>
        <ListView SeparatorColor="Transparent" 
                  CachingStrategy="RecycleElement"
                  RowHeight="{OnIdiom 190, Phone=190, Tablet=380}"
                  x:Name="listView"
                  VerticalScrollBarVisibility="Always"
                  BackgroundColor="Transparent"
                  SelectionMode="None" 
                  ItemTemplate="{StaticResource toolTipTemplate2}" />
    </ContentPage.Content>
</ContentPage>

页面后台代码

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ListPage: ContentPage
{
    public ListPage(List<MyItem> list)
    {
        InitializeComponent();
        listView.ItemsSource = list;
    }
}

观察到的GC运行日志

[Mono] GC_TAR_BRIDGE bridges 36 objects 36 opaque 0 colors 36 colors-bridged 36 colors-visible 36 xref 0 cache-hit 0 cache-semihit 0 cache-miss 0 setup 0.19ms tarjan 0.04ms scc-setup 0.05ms gather-xref 0.02ms xref-setup 0.01ms cleanup 0.15ms
[Mono] GC_BRIDGE: Complete, was running for 26.75ms
[Mono] GC_MINOR: (Nursery full) time 5.79ms, stw 8.16ms promoted 786K major size: 11600K in use: 10156K los size: 10240K in use: 8644K

已发现的逻辑疏漏

  • 自定义控件存在强引用事件泄漏:构造函数中直接为Clicked事件订阅了实例方法Checkbox_OnClick,事件发布方会持有订阅方的强引用,即使控件脱离可视树,只要事件发布方还在内存中,订阅的控件实例就无法被GC回收
  • RecycleElement缓存机制被破坏:正常情况下该策略会复用已创建的ViewCell实例,不会在页面导航后持续触发构造函数;出现持续构造的情况,本质是旧实例被强引用导致无法进入复用池,框架只能不断创建新的实例
  • 未主动断开页面销毁时的绑定链路:ListView的双向绑定、编译绑定会持有数据源和控件的双向引用,页面导航退出时如果没有清空数据源,会形成跨页面的引用链,打断GC回收流程

内存释放操作方案

  • 页面退出时主动清空ListView数据源:
    在页面的OnDisappearing生命周期中,将ItemsSource置空,断开绑定链路:
    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        listView.ItemsSource = null;
    }
    
  • 修正自定义控件的事件订阅逻辑:
    不要在构造函数中直接绑定长生命周期事件,改为跟随控件的父级挂载状态动态绑定,在控件脱离可视树时移除订阅:
    protected override void OnParentSet()
    {
        base.OnParentSet();
        if (Parent == null)
        {
            // 控件从可视树移除,解绑事件
            Clicked -= Checkbox_OnClick;
        }
        else
        {
            // 控件挂载到新的父级,重新绑定事件
            Clicked += Checkbox_OnClick;
        }
    }
    
  • 关于GC回收的认知修正:
    Mono运行时的垃圾回收不是即时触发的,仅当内存达到阈值时才会执行回收流程。如果没有持续的对象分配行为,偶发的GC日志属于正常现象;只有出现页面移除后持续的对象构造、内存占用持续上涨的情况,才需要排查引用泄漏问题。

内容的提问来源于stack exchange,提问作者Adam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.25 16:06:05