Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 772
indot_brad Avatar asked Sep 06 '25 03:09

indot_brad


1 Answers

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.

like image 57
Nick Butler Avatar answered Sep 07 '25 19:09

Nick Butler