Example of RestSharp ASYNC client.ExecuteAsync<T> () works

半世苍凉 提交于 2019-12-04 09:00:34

问题


Could someone please help me modify the code below:

client.ExecuteAsync(request, response => {
    Console.WriteLine(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?

I tried this but doesnt' work:

    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);
});

}

The above code is from https://github.com/restsharp/RestSharp


回答1:


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;
}

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




回答2:


With the help of @spender, this is what i got:

You can add new file in RestSharp project, and add this code:

public partial class RestClient
{
    public Task<IRestResponse<T>> ExecuteAsync<T>(IRestRequest request)
    {
        var tcs=new TaskCompletionSource<IRestResponse<T>>();

        this.ExecuteAsync(request, response => 
            {
                tcs.SetResult(
                    Deserialize<T>(request, response)
                );
            });

    return tcs.Task;
    }       
}

This will practically return the full response, with status code and everything, so you can check if the status of the response is OK before getting the content, and you can get the content with:

response.Content



回答3:


From reading the code it looks like you want to use ExecuteAsGet or ExecuteAsPost instead of the async implementation.

Or maybe just Execute- not sure exactly what type Client is.



来源:https://stackoverflow.com/questions/12232653/example-of-restsharp-async-client-executeasynct-works

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!