1

I have some code that's bugging me due to my lack of knowledge on Async in c#.

public async Task<T> GetAsync(string apiURL)
    {
        _client = await SchedulerHttpClient.ClientTask;

        var response = await _client.GetAsync(apiURL);

        if(response.IsSuccessStatusCode)
        {
            var responseContent = response.Content.ReadAsAsync<T>();
            //todo: check
            return responseContent.Result;
        }
        else
        {
            return default(T);
        } 
    }

My question is i want to get the content from the response, in my example i await the response so i can obtain the content.

However should i use await to get the content, if not then how do i get the content from the response if i don't await.

lemunk
  • 2,616
  • 12
  • 57
  • 87
  • 2
    As a general rule, If you are receiving a `Task`, you should `await` it (if you can) – Matias Cicero Mar 30 '17 at 12:47
  • I agree with @MatiasCicero, and I personally would do `return await responseContent;` instead. – juharr Mar 30 '17 at 12:52
  • ah my lead is suggesting i refactor my code and don't bother with awaits... gave no reason as to why but i questioned my code. I do wonder though, this result gets fired but my controller doesn't get notified (no need to) instead theirs a logging section that checks all this separate, in that case i shouldn't await at all? – lemunk Mar 30 '17 at 12:53
  • Note that using `await` means that you don't block a thread. If you use `Task.Wait` or `Task.Result` you block the thread. That's the main (but not only) difference and it would mostly effect performance when under load. – juharr Mar 30 '17 at 12:54
  • With responseContent.Result you block the thread until the asynchronous operation is complete; it is equivalent to calling the Wait method. (https://msdn.microsoft.com/en-us/library/dd321468(v=vs.110).aspx#Anchor_2) – Pedro Perez Mar 30 '17 at 12:55

0 Answers0