C# 为什么这个重新加载方法会在可见的一秒内阻塞 UI

C# why does this reload method block the UI for a visible second

我有一个调用 API 的函数,然后将数据绑定到视图(以及两者之间的大量本地计算。)

简而言之,这个方法是这样的:

        private async Task LoadMoreAds()
        {
            Task.Run(async () =>
            {

                await ...random api then
                ... do something with the results then 
                ... bind the views 

            });
        }

此方法是从 UI 事件处理程序调用的:

     private async void listview_allAds_FlowItemAppearing(object sender, ItemVisibilityEventArgs e)
{
            TinyAd current = e.Item as TinyAd;
             if (current == contentOfListView[contentOfListView.Count - 2])
                {
                    if (!isCurrentlyLoading)
                        await LoadMoreAds();     
                 }        
            }
    
}

我认为我正在正确执行所有异步和等待操作。

但我仍然看到 UI 在用户快速滚动时重新加载时出现轻微挂起- 此外,帧率不是 60,而是平均 30。

有什么我可以优化的吗?

这里有一些建议。

  1. 停止在另一个任务中使用一个任务,只需删除内部 Task.Run .

  2. 不要await LoadMoreAds外,使用awaitLoadMoreAds方法。

  3. 在 xaml 中而不是在 LoadMoreAds 方法中执行 binding 东西,只需请求数据并修改绑定源(不要'不涉及视图操作,否则您需要在主线程上更新它)。

参考这里的示例:https://montemagno.com/load-more-items-at-end-of-listview-in/