Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I await ReadAsStringAsync() if I awaited the response that I'm performing ReadAsStringAsync() on?

Should I await ReadAsStringAsync() if I awaited the response on which I'm performing ReadAsStringAsync()? To clarify further, what is the difference or the right way between the following? Are they effectively the same?

var response = await httpClient.GetAsync("something"); var content = await response.Content.ReadAsStringAsync(); return new AvailableViewingTimesMapper().Map(content); 

OR

var response = await httpClient.GetAsync("something"); var content = response.Content.ReadAsStringAsync(); return new AvailableViewingTimesMapper().Map(content.Result); 
like image 393
Toby Holland Avatar asked Jan 28 '15 21:01

Toby Holland


1 Answers

Your first example is the correct one. The second example does not yield during the asynchronous operation. Instead, by getting the value of the content.Result property, you force the current thread to wait until the asynchronous operation has completed.

In addition, as commenter Scott Chamberlain points out, by blocking the current thread it is possible you could introduce the possibility of deadlock. That depends on the context, but a common scenario for await is to use that statement in the UI thread, and the UI thread needs to remain responsive for a variety of needs, but including to be able to actually handle the completion of an awaited operation.

If you avoid the second pattern, i.e. retrieving the value of the Result property from a Task you don't know has completed, not only can you ensure efficient use of your threads, you can also ensure against this common deadlock trap.

like image 163
Peter Duniho Avatar answered Oct 05 '22 06:10

Peter Duniho