Xamarin中的Task.ConfigureAwait(false)-使用安全/建议使用? [英] Task.ConfigureAwait(false) in Xamarin - safe to use / recommended to use?

查看:159
本文介绍了Xamarin中的Task.ConfigureAwait(false)-使用安全/建议使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经验法则:如果它不是与UI相关的方法,请使用Task.ConfigureAwait(false).

Rule of thumb says: if it's not a UI related method, use Task.ConfigureAwait(false).

如果我有一个接受接口IUIAccess的PCL核心库,该怎么办. 然后,核心库中的视图模型具有一种方法:

What if I have a PCL core library which accepts an interface IUIAccess. The view model in the core library then has a method:

public Task ViewModelLoginAsync()
{
  bool success = await loginService.ServiceLoginAsync();
  if(!success)
  {
    uiAccess.ShowInfoDialog("Login failed.");
  }
}

IUIAccess在iOS上将显示UIAlertView.

IUIAccess would show a UIAlertView on iOS.

我现在的假设是:如果我从UIViewController呼叫ViewModelLoginAsync,则不应配置为FALSE.显然是UI代码. 但是,对ServiceLoginAsync的调用可以使用configure await false.这样对吗? 是出于性能,内存使用等原因,还是只是一种很好的做法还是真的建议这样做?

My assumption would now be: if I call ViewModelLoginAsync from my UIViewController I should not configure await to FALSE. It clearly is UI code. However the call to ServiceLoginAsync could use configure await false. Is this correct? Is it just good practice or really recommended because of performance, memory usage, ...?

推荐答案

首先,我建议(尽可能)从VM调用视图.我更喜欢使用数据绑定或某种类型的消息总线.

First, I recommend (as much as possible) not to call from the VM into the view. I would prefer to use data binding or a message bus of some kind.

也就是说,您将不会在ViewModelLoginAsync中使用ConfigureAwait(false),因为它需要在UI上下文中恢复(如果通过数据绑定而不是显式调用进行更新,则也是如此).但是,出于我在 MSDN文章中描述的原因,ServiceLoginAsync应该使用ConfigureAwait(false)(主要是性能).

That said, you would not use ConfigureAwait(false) in ViewModelLoginAsync, since it needs to resume on the UI context (this is also true if you update via data binding instead of an explicit call). However ServiceLoginAsync should use ConfigureAwait(false) for the reasons I describe in my MSDN article (primarily performance).

这篇关于Xamarin中的Task.ConfigureAwait(false)-使用安全/建议使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆