2014-03-06 46 views
1

什么是重构这个代码使用异步/等待最好的方法?此代码段是从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 
       })); 
    } 

什么是重构这个代码使用异步/等待最好的方法?

回答

3

你可以只是这样做:

partial async void Login() 
{ 
    //some ui related code 
    await loginViewModel.LoginAsync(); 
    //go to different view 
} 

你不需要切换线程作为await捕获当前SynchroniztionContext和发布方法的其余部分在同一背景下的延续。对于UI线程,这基本上意味着go to different view部分也将在UI thrad上执行。

你或许应该检查LoginAsync操作以及

private async void Login() 
{ 
    //some ui related code 
    if(await loginViewModel.LoginAsync()) 
    { 
     //go to different view 
    } 
    else 
    { 
     // login failed 
    } 
} 

我不会任何进一步的重构这个,因为它是非常简单的结果。

+1

否则将是一件好事,但部分方法将是一个问题,因为该方法需要被打上异步。 – SKall

+0

感谢您的快速响应!有没有机会重构LoginService实现? –

+0

我不会担心任何进一步的重构。通常你提供一个没有'CancellationToken'的实现,但你已经有效地实现了deafult'的值。 –

1

难重构延迟到任何有意义的东西,但它仅仅是这样的:

public class LoginService : ILoginService 
{  
    public async Task<bool> LoginAsync (string username, string password, CancellationToken cancellationToken = default(CancellationToken)) 
    { 
     await Task.Delay(TimeSpan.FromMilliseconds(1000), cancellationToken); 
     return true; 
    } 
} 

延迟将与F.E.被替换异步网络呼叫到服务器以确认登录。

+0

假设我们有一些http调用,而不是延迟... –

+0

是的,当我编辑时,你击败了我。任何可以等待的事情都可以实现,你不需要开始任务。 – SKall