0

I am trying to understand the reason for the differences in two articles describing the same thing (calling a JSON rest webservice).

Article 1: Calling a Web API From a .NET Client in ASP.NET Web API 2

Article 2: Calling ASP.NET WebAPI using HttpClient

The differences are:

HttpResponseMessage response = await client.GetAsync("api/products/1");

vs

HttpResponseMessage response = client.GetAsync(url).Result;

and

Product product = await response.Content.ReadAsAsync>Product>();

vs

var users = response.Content.ReadAsAsync<Users>().Result;

My confusion is not with the asynchronous nature of the calls and I understand the functionality of the await statement. My confusion stems from the .Result at the end of the CodeProject examples (BTW the Code Project examples work for me) and the fact that the Microsoft article does not have them.

If I copy the Microsoft article code I get compiler warnings wanting me to add Task around my return type. What am I missing?

Thanks

Talib
  • 335
  • 3
  • 15
  • possible duplicate of [Calling async method synchronously](http://stackoverflow.com/questions/22628087/calling-async-method-synchronously) – CodeCaster Mar 02 '15 at 14:08
  • This has nothing to do with WebAPI or HttpClient, but with async/await. In a synchronous call, you use `.Result` to synchronously obtain the result of an async call. See [Calling async method synchronously](http://stackoverflow.com/questions/22628087/calling-async-method-synchronously). – CodeCaster Mar 02 '15 at 14:09

1 Answers1

1

ABCAsync methods return a Task<something> to encapsulate the state of the maybe-failed/completed/pending operation. Once the operation completes the returned values Result property will contain the actual return value.

With the compiler support – the await keyword – the compiler hides this detail.

Hence using await you just see the result of the operation (the Task<T> instance is hidden), but when not using the compiler support you have to deal with the details.

NB. Accessing Task<T>.Result when the task has not completed will block; if it has failed then it will throw. Thus

var x = obj.ABCAsync().Result;

acts very much like calling the blocking version of the method; but with the extra overheads of the compiler helpers.

Richard
  • 106,783
  • 21
  • 203
  • 265