重构此代码以使用 async/await 的最佳方法是什么?此代码片段来自 Xamarin Field Services Sample App
ViewModel 的数据提供者接口(interface)
public interface ILoginService {
Task<bool> LoginAsync (string username, string password, CancellationToken cancellationToken = default(CancellationToken));
}
登录的接口(interface)实现。这里只是为了假网络调用而 sleep ......
public class LoginService : ILoginService {
public Task<bool> LoginAsync (string username, string password, CancellationToken cancellationToken = default(CancellationToken)) {
return Task.Factory.StartNew (() => {
Thread.Sleep (1000);
return true;
}, cancellationToken);
}
}
按钮点击处理程序
partial void Login () {
//some ui related code
loginViewModel
.LoginAsync ()
.ContinueWith (_ =>
BeginInvokeOnMainThread (() => {
//go to different view
}));
}
重构此代码以使用 async/await 的最佳方法是什么?
请您参考如下方法:
你可以这样做:
partial async void Login ()
{
//some ui related code
await loginViewModel.LoginAsync ();
//go to different view
}
您不需要切换线程,因为 await 捕获当前的 SynchroniztionContext 并将该方法的其余部分作为同一上下文的延续发布。对于 UI 线程,这实质上意味着 go to different view 部分也将在 UI 线程上执行。
您可能还应该检查 LoginAsync 操作的结果
private async void Login ()
{
//some ui related code
if(await loginViewModel.LoginAsync())
{
//go to different view
}
else
{
// login failed
}
}
我不会进一步重构它,因为它非常简单。
