【问题标题】:Lag in updating UI with databinding due to calling an async method?由于调用异步方法而延迟使用数据绑定更新 UI?
【发布时间】:2018-05-20 09:45:19
【问题描述】:

在 Xamarin.Forms 应用程序中,我将布尔值 Upvoted 属性绑定到 ImageSource 属性(通过转换器),以在两个图标之间切换,指示用户是否支持图片与否,我将Upvoted 值与UserIdImageId 一起发送到服务器,然后我更新图标,这会导致图标更改有点滞后

我的方法的第一个(慢)版本:

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

然后我改成这样:

 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;

        }

行:

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

应该通过数据绑定立即更新 UI:

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

所以我期待的是图像会立即更新(就像我注释掉调用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;

        }

但问题仍然存在,UI 滞后,就像在等待服务器完成数据更新一样。

【问题讨论】:

  • 我们怎么知道注释代码在你没有发布的时候是什么样子的。你也明白同步和异步之间的区别吗?
  • 根据您的标题,它根本不起作用,但是在阅读了问题之后,它起作用了,但只是滞后了。这有点令人困惑,您能否更新问题以正确反映问题?
  • 最小化,修改过,请再看一遍

标签: c# multithreading asynchronous xamarin async-await


【解决方案1】:

这里需要的重要信息是SendVote 所做的。它可能会也可能不会阻塞调用者的线程,无论您是否使用await 调用它。

我不确定,但您的困惑可能来自于认为await 本身会导致SendVote 方法在单独的线程上运行。相反,await 关键字仅影响在完成指定的Task(在您的情况下为Task&lt;bool&gt;)后如何安排方法的其余部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2018-06-13
    相关资源
    最近更新 更多