简体   繁体   中英

Lag in updating UI with databinding due to calling an async method?

In a Xamarin.Forms app I'm binding a boolean Upvoted property to an Image 's Source property (through a converter), to switch between two icons, indicating whether the user has upvoted for a picture or not, I'm sending the Upvoted value along with the UserId and ImageId to the server, then I update the icon, that causes a little lag for the icon to change

the first (slow) version of my method:

private async void OnVoting(ImageVotingModel image)
     {
          if (await SendVote(image)) //is responsible for updating database, it returns true only when the voting is updated successfully
             Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted;
     }

and then I changed to this:

 private async void OnVoting(ImageVotingModel image)
        {
            if (IsBusy)// it's true when there is a work being done on server
                return;
            Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted; //with data-binding, once the Upvoted change the icon should be updated
            if (!await SendVote(image))
                Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted;

        }

the line:

Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted; 

is supposed to update the UI immediately through the databinding:

 <Image Source="{Binding UpVoted, Converter={StaticResource boolToImage}}"/>

so what I was expecting is that the image will be updated immediately (like when I commented out the code that calls SendVote ::

private async void OnVoting(ImageVotingModel image)
        {
            if (IsBusy)// it's true when there is a work being done on server
                return;
            Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted; //with data-binding, once the Upvoted change the icon is updated
           // if (!await SendVote(image))
             //   Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted;

        }

but the problem still there, the UI lags like it's waiting the server to finish updating its data.

The important piece of information needed here is what SendVote does. It may or may not block the caller's thread, regardless of whether you call it using await .

I'm not certain, but your confusion may come from thinking that await by itself causes the SendVote method to run on a separate thread. Rather, the await keyword only affects how the remainder of the method is scheduled upon completion of the specified Task ( Task<bool> in your case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM