0

I am using an async method synchronously using the Task.Wait() method, but when the call is complete I would like to access to the object templated by the Task<>.

Task<HttpResponseMessage> message = _httpClient.GetAsync(Globals.ENDPOINT_URI + Uri.EscapeDataString(query));
message.Wait();

How do I access the HttpResponseMessage of the message object ?

Thank you

Toto
  • 736
  • 9
  • 33
  • 7
    `message.Result` – juharr Aug 11 '17 at 17:55
  • you could also use `var message` – r3dst0rm Aug 11 '17 at 17:56
  • 2
    Possible duplicate of [Get result from async method](https://stackoverflow.com/questions/20884604/get-result-from-async-method) or [How to get returned value of async Task methdoName()?](https://stackoverflow.com/questions/26269066/how-to-get-returned-value-of-async-taskstring-methdoname) – Lance U. Matthews Aug 11 '17 at 18:17

1 Answers1

4

You'll want to use async/await, as it's considered a bad practice to use Wait and Result. Your code would be updated to the following:

HttpResponseMessage message =
    await _httpClient.GetAsync(Globals.ENDPOINT_URI + Uri.EscapeDataString(query));

await will both wait for the call to complete and provide the result, which will sit in your message variable.

There are plenty of good resources on the Internet and great answers here on Stack Overflow regarding async/await, introduced in C# 5. Here's one page to get you started: https://learn.microsoft.com/en-us/dotnet/csharp/async.

EDIT: Here's a good resource on the Result problem: https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203