【问题标题】:Waiting for ExecuteAsync() result等待 ExecuteAsync() 结果
【发布时间】:2013-03-15 14:31:15
【问题描述】:

我的 RestSharp 实现存在以下问题。如何让我的应用程序在继续之前等待 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;
    }   

【问题讨论】:

  • 来自RestSharp库,一种WebClient
  • 什么是连接?我在 RestSharp 中找不到这个类

标签: c# asynchronous windows-phone-8 restsharp


【解决方案1】:

我认为您错过了 Task 和 async/await 模式的要点。

您不会在此方法中等待,但由于您返回的是 Task&lt;&gt;,因此它允许调用者异步等待它(如果选择)。

调用者应该是这样的:

 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&lt;Connection&gt; 已转入Connection

鉴于:您的第一个代码 sn-p 看起来不错。

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

【讨论】:

  • 感谢您的解决方案,但我仍然遇到同样的问题。方法public Task&lt;Connection&gt; Connect(string userId, string password) {...}返回tcs.task无需等待client.ExecuteAsync&lt;Connection&gt;(...)的执行所以结果总是null
  • 是的,这正是它应该做的。只有await它才会得到结果。
猜你喜欢
  • 1970-01-01
  • 2017-10-30
  • 2017-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多