2

我的 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;
    }   
4

1 回答 1

4

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

您不会在此方法内等待,但因为您返回 aTask<>它允许调用者异步等待它,如果选择它。

调用者将是这样的:

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

      //... do something with result
 }

编译器知道如何制作这段代码,这与同步(阻塞)等价物非常相似,并将其转换为异步代码。

注意asyncandawait关键字,并注意Task<Connection>已经转入Connection

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

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

于 2013-03-15T20:31:31.520 回答