egbrad
egbrad

Reputation: 2417

RestSharp: ExecuteAsync<T> never responds

I am trying to make an async get request using ExecuteAsync<T>, but it never responds. The confusing thing to me is that ExecuteAsync works, as do both synchronous methods Execute and Execute<T>.

Here is my code:

var restClient = new RestClient("http://localhost:44268/api/");
var request = new RestRequest("jobs/{id}", Method.GET);
request.AddUrlSegment("id", "194");

// works
var req1 = restClient.Execute(request).Content;

// works
var req2 = restClient.Execute<Job>(request).Content;

// works
var req3 = restClient.ExecuteAsync(request, (restResponse) =>
{
    var test = restResponse.Content;
    Console.WriteLine(test);
});

var req4 = restClient.ExecuteAsync<Job>(request, (restResponse) =>
{
    // this code is never reached
    var test = restResponse.Content;
    Console.WriteLine(test);
});

It is successfully making the call to the API, but it just never calls back. Why? Am I doing something wrong?

Upvotes: 4

Views: 6883

Answers (4)

Sunil Singh
Sunil Singh

Reputation: 1

IRestResponse loginResponse = new RestResponse();
                    TaskCompletionSource<IRestResponse> tcs = new TaskCompletionSource<IRestResponse>();

//Task task = new Task(() => {client.ExecuteAsync<RestResponse>(request, tcs.SetResult);});// Lambda and anonymous method  
Task task = new Task(() =>client.ExecuteAsync<RestResponse>(request, tcs.SetResult)); // Lambda and named method                    
task.Start();
loginResponse = await tcs.Task;

Upvotes: 0

sunil singh
sunil singh

Reputation: 21

public  Task<IRestResponse> ExecuteAsync<T>(RestRequest request, RestClient client)
{
  EventWaitHandle executedCallBack = new AutoResetEvent(false);
  TaskCompletionSource<IRestResponse> tcs = new TaskCompletionSource<IRestResponse>();

IRestResponse res = new RestResponse();   
    try
    {
      var asyncHandle = client.ExecuteAsync<RestResponse>(request, response =>
        {
          res = response;
          tcs.TrySetResult(res);
          executedCallBack.Set();
        });


    }
    catch (Exception ex)
    {
      tcs.TrySetException(ex);
    }

    return tcs.Task;
}

Upvotes: 0

egbrad
egbrad

Reputation: 2417

This was resolved by upgrading to the latest version of RestSharp.

Upvotes: 2

Nick Butler
Nick Butler

Reputation: 24383

ExecuteAsync is asynchronous.

That means the calls to it return immediately without waiting for a response.

Then your program continues as normal. If this is a console app and execution comes to the end of your Main method, the whole program will exit.

So, you have a race condition. Most of the time, your program will exit before the continuations ( the lambda callbacks ) have a chance to run.

Try putting a Console.ReadLine(); call at the end of your Main method to prevent early exit.

Upvotes: 2

Related Questions