Example of RestSharp ASYNC client.ExecuteAsync () works

后端 未结 3 2093
孤城傲影
孤城傲影 2021-02-07 05:56

Could someone please help me modify the code below:

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

相关标签:
3条回答
  • 2021-02-07 06:33

    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.

    0 讨论(0)
  • 2021-02-07 06:47

    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

    0 讨论(0)
  • 2021-02-07 06:56

    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
    
    0 讨论(0)
提交回复
热议问题