innom
innom

Reputation: 1125

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

I have a function that makes a call to an API, and then binds the data to the view (along with a lot of local calculations in between.)

In short, this method looks like this:

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

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

            });
        }

This method is called from UI event handler:

     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();     
                 }        
            }
    
}

I think I am doing all my async and awaits correctly.

But still i am seeing a slight hang on UI reload when the user scrolls fast- Also the framerate is not at 60, rather at avg of 30.

Is there something I can optimize?

Upvotes: 1

Views: 81

Answers (1)

ColeX
ColeX

Reputation: 14475

Here are some suggestions .

  1. Stop using a Task inside another Task, just remove the inner Task.Run .

  2. Do not await LoadMoreAds outside , use await inside LoadMoreAds method.

  3. Do the binding stuff in xaml not inside LoadMoreAds method , just request data and modify the binding source(don't involve view manipulation otherwise you need to update it on main thread ).

Refer to the sample here : https://montemagno.com/load-more-items-at-end-of-listview-in/.

Upvotes: 2

Related Questions