什么是重构这个代码使用异步/等待最好的方法?此代码段是从Xamarin Field Services Sample AppXamarin:重构使用异步/等待
数据提供接口的ViewModels
public interface ILoginService {
Task<bool> LoginAsync (string username, string password, CancellationToken cancellationToken = default(CancellationToken));
}
接口实现登录。这里只是睡觉假冒网络电话...
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
}));
}
什么是重构这个代码使用异步/等待最好的方法?
否则将是一件好事,但部分方法将是一个问题,因为该方法需要被打上异步。 – SKall
感谢您的快速响应!有没有机会重构LoginService实现? –
我不会担心任何进一步的重构。通常你提供一个没有'CancellationToken'的实现,但你已经有效地实现了deafult'的值。 –