webworm
webworm

Reputation: 11019

".Result" doesn't not seem to be acting synchronously

I have an API call that makes use of .Result to act synchronously.

HttpResponseMessage response = client.PostAsync("api/updatelastname", new StringContent(string.Format("UserId={0}&LastName={1}", userId, lastName),  Encoding.UTF8, "application/x-www-form-urlencoded")).Result;

To see if the API has completed successfully I use the following if..then statement before proceeding.

if (!response.IsSuccessStatusCode)
{
  // Something went wrong
}

What I am confused about is sometimes the api call completes without issue and then sometimes it does not. It seems like at times the code does not wait for the API call to complete and therefore the response.IsSuccessStatusCode is false.

Ideally I think it would be best to make the method async and use the await keyword on the API call, however the web app only targets .NET 4 at the moment and async and await are not supported until .NET v4.5.

Any thoughts on how I can ensure the API call completes before checking the response.IsSuccessStatusCode? Without moving to .NET v4.5+?

Upvotes: 0

Views: 47

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456507

the web app only targets .NET 4 at the moment and async and await are not supported until .NET v4.5.

It's the client (the one calling PostAsync), not the web app, that needs to support await. I'll assume that you mean that the client is a web app.

sometimes the api call completes without issue and then sometimes it does not.

Sometimes it does not complete, you mean? As in, the code never returns from Result?

There are some scenarios where Result will deadlock, but I'd be surprised to find one on ASP.NET (to my knowledge, all Result deadlocks with HttpClient are only on some mobile platforms).

It seems like at times the code does not wait for the API call to complete and therefore the response.IsSuccessStatusCode is false.

What you're suspecting isn't possible. Result will block until the HTTP request completes. If IsSuccessStatusCode returns false, then that's because the API returned a non-success status code.

Upvotes: 1

Related Questions