Example of RestSharp ASYNC client.ExecuteAsync () works

后端 未结 3 2096
孤城傲影
孤城傲影 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: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 (assuming response.Content is a string):

    Task GetResponseContentAsync(...)
    {
      var tcs=new TaskCompletionSource();
      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 as it's pretty core.

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

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

提交回复
热议问题