You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin Form刷新ListView时UI阻塞,使用async请求加载服务端数据为何仍出现该问题?

问题原因

  1. ObservableCollection<T>的Add方法每执行一次都会触发CollectionChanged事件通知UI刷新,循环批量添加数据时会触发数十到数百次UI重绘,所有重绘操作都在主线程执行,直接导致UI阻塞。
  2. PropertyChanged回调未做属性名校验,NotifyTask的状态属性(如IsLoading、IsCompleted)变更时都会触发回调执行循环逻辑,产生大量无意义的计算开销。
  3. 所有循环添加逻辑都运行在UI主线程,数据量越大阻塞时间越长。

解决方案

  • 方案1:使用支持批量添加的自定义集合
    继承ObservableCollection实现支持批量添加的扩展类,批量插入完成后仅触发一次UI通知:
public class RangeObservableCollection<T> : ObservableCollection<T>
{
    private bool _suppressNotification = false;

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        if (!_suppressNotification)
            base.OnCollectionChanged(e);
    }

    public void AddRange(IEnumerable<T> list)
    {
        if (list == null)
            throw new ArgumentNullException(nameof(list));

        _suppressNotification = true;
        foreach (T item in list)
        {
            Items.Add(item);
        }
        _suppressNotification = false;
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
}

替换原有集合类型后修改回调逻辑即可:

// 声明改为RangeObservableCollection
public RangeObservableCollection<VideoFile> VideoFiles { get; private set; } = new RangeObservableCollection<VideoFile>();

private void VideoFilesPropertyChanged(object sender, PropertyChangedEventArgs propertyName)
{
    // 只监听Result属性变更
    if (propertyName.PropertyName == nameof(NotifyTask<List<VideoFile>>.Result))
    {
        var result = ((NotifyTask<List<VideoFile>>)sender).Result;
        VideoFiles.Clear();
        // 批量添加仅触发一次UI刷新
        VideoFiles.AddRange(result);
    }
}
  • 方案2:直接替换集合引用触发整体刷新
    给集合属性添加属性变更通知,拿到接口数据后直接生成新的集合赋值,避免循环插入:
private ObservableCollection<VideoFile> _videoFiles;
public ObservableCollection<VideoFile> VideoFiles
{
    get => _videoFiles;
    set 
    { 
        _videoFiles = value;
        OnPropertyChanged(); // 所在ViewModel需实现INotifyPropertyChanged接口
    }
}

private void VideoFilesPropertyChanged(object sender, PropertyChangedEventArgs propertyName)
{
    if (propertyName.PropertyName == nameof(NotifyTask<List<VideoFile>>.Result))
    {
        var result = ((NotifyTask<List<VideoFile>>)sender).Result;
        // 一次性赋值触发单次UI刷新
        VideoFiles = new ObservableCollection<VideoFile>(result);
    }
}
  • 方案3:配合UI虚拟化优化渲染性能
    数据量超过50条时建议开启ListView的单元格复用机制,减少渲染开销:
<ListView ItemsSource="{Binding VideoFiles}"
          CachingStrategy="RecycleElement"
          HasUnevenRows="True">
    <!-- 单元格模板 -->
</ListView>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 01:06:03