RestSharp ASYNC client.ExecuteAsync<T> 示例() 作品 [英] Example of RestSharp ASYNC client.ExecuteAsync&lt;T&gt; () works

查看:167
本文介绍了RestSharp ASYNC client.ExecuteAsync<T> 示例() 作品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能帮我修改下面的代码:

Could someone please help me modify the code below:

client.ExecuteAsync(request, response => {
    Console.WriteLine(response.Content);
});

基本上我想使用上面的 ExecuteAsync 方法但不想打印但将 response.Content 返回给调用者.

Basically I want to use ExecuteAsync method above but don't want to print but return response.Content to the caller.

有什么简单的方法可以实现吗?

Is there any easy way to achieve this?

我试过了,但没有用:

    public T Execute<T>(RestRequest request) where T : new()
        {
            var client = new RestClient();
            client.BaseUrl = BaseUrl;
            client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
            request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment); // used on every request
            var response = client.ExecuteAsync(request, response => {
    return response.data);
});

}

以上代码来自https://github.com/restsharp/RestSharp

推荐答案

有个问题……你不能返回异步传递的值,因为你的调用方法已经返回了.在获得结果之前阻止调用者失去了使用 ExecuteAsync 的意义.在这种情况下,我会返回一个 Task(假设 response.Content 是一个字符串):

There's the thing... you can't return an asynchronously delivered value, because your calling method will already have returned. Blocking the caller until you have a result defeats the point of using ExecuteAsync. In this case, I'd return a Task<string> (assuming response.Content is a string):

Task<string> GetResponseContentAsync(...)
{
  var tcs=new TaskCompletionSource<string>();
  client.ExecuteAsync(request, response => {
    tcs.SetResult(response.Content);
  });
  return tcs.Task;
}

现在,当任务完成时,您就有了价值.当我们转向 c#5 async/await 时,您应该习惯于在 Task 方面说明异步,因为它非常核心.

Now, when the task completes, you have a value. As we move to c#5 async/await, you should get used to stating asynchrony in terms of Task<T> as it's pretty core.

http://msdn.microsoft.com/en-us/library/dd537609.aspx

http://msdn.microsoft.com/en-us/library/hh191443.aspx

这篇关于RestSharp ASYNC client.ExecuteAsync<T> 示例() 作品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆