2013-03-15 95 views
2

我的RestSharp实现有以下问题。如何在继续之前让我的应用程序等待来自ExecuteAsync()的响应?等待ExecuteAsync()结果

我尝试了不同的解决方案:

优先(该方法不等待ExecuteAsync响应):

public Task<Connection> Connect(string userId, string password) 
    { 
     var client = new RestClient(_baseUrl) 
      { 
       Authenticator = new SimpleAuthenticator("user", userId, 
        "password", password) 
      }; 
     var tcs = new TaskCompletionSource<Connection>(); 
     var request = new RestRequest(AppResources.Authenticating); 
     client.ExecuteAsync<Connection>(request, response => 
      { 
       tcs.SetResult(new JsonDeserializer(). 
        Deserialize<Connection>(response)); 
      }); 
     return tcs.Task; 
    } 

所以我想这一点,但应用程序冻结:

public Task<Connection> Connect(string userId, string password) 
    { 
     EventWaitHandle executedCallBack = new AutoResetEvent(false); 
     var client = new RestClient(_baseUrl) 
      { 
       Authenticator = new SimpleAuthenticator("user", userId, 
        "password", password) 
      }; 
     var tcs = new TaskCompletionSource<Connection>(); 
     var request = new RestRequest(AppResources.Authenticating); 
     client.ExecuteAsync<Connection>(request, response => 
      { 
       tcs.SetResult(new JsonDeserializer(). 
          Deserialize<Connection>(response)); 
       executedCallBack.Set(); 
       }); 
     executedCallBack.WaitOne(); 
     return tcs.Task; 
    } 
+0

什么是RestClient? – Default 2013-03-15 16:06:51

+1

它来自'RestSharp'库,一种'WebClient' – user2169047 2013-03-16 09:41:39

+0

什么是连接?我无法在RestSharp中找到此课程 – adrian4aes 2015-12-09 14:34:02

回答

3

我想你错过了任务和异步/等待模式的要点。

你不用等待这个方法,但是因为你要返回一个Task<>它允许调用者在它选择的时候等待它。

呼叫者会是这样的:

public async void ButtonClick(object sender, RoutedEventArgs args) 
{ 
    Connection result = await restClient.Connect(this.UserId.Text, this.Password.Text); 

     //... do something with result 
} 

编译器知道如何使这个代码,这是非常相似的同步(阻塞)等同,并把它变成异步代码。

请注意asyncawait关键字,并注意Task<Connection>已转入Connection

鉴于:您的第一个代码片段看起来不错。

第二个可能会导致一个问题,因为你引入另一个线程机制(即信号量AutoResetEvent)。另外@HaspEmulator是正确的 - 如果这是在UI线程上,这是已知的WP应用程序死锁。

+0

感谢您的解决方案,但我仍然遇到同样的问题。 方法 '公共任务连接(字符串userid,字符串密码) {...}' 回报'tcs.task'without等待 'client.ExecuteAsync 执行(.. 。)' 所以结果总是为空 – user2169047 2013-03-16 09:57:32

+1

是的,这正是它应该做的。如果你“等待”它,你只会得到一个结果。 – 2013-03-16 10:05:18

0

这看起来非常类似于周围有许多人的问题:您不应该在执行WebRequest时进行阻塞(直接或间接地通过其他库)。这似乎陷入僵局。避免这种情况。