c# - Why await both the asynchronous request and the reading of its contents? -
why necessary in .net web api have a method reads content of http response asynchronously, given there method make request asynchronously? said way, if using httpclient.getasync
(or postasync
, or putasync
, etc), code more asynchronous reading content out asynchronously? if so, how/why?
is this:
using (var client = new httpclient()) { var response = await client.getasync("..."); response.ensuresuccessstatuscode(); return await response.content.readasasync<foo>(); }
better this:
using (var client = new httpclient()) { var response = await client.getasync("..."); response.ensuresuccessstatuscode(); return response.content.readasasync<foo>().result; }
and why?
why necessary in .net web api have a method reads content of http response asynchronously, given there method make request asynchronously?
because can. 2 methods different things. first send network request on wire, second reads received stream
.
as both making network request , reading stream io bound operations, can take advantage of async api expose.
if using httpclient.getasync (or postasync, or putasync, etc), code more asynchronous reading content out asynchronously? if so, how/why?
it sounds bit weird "more async". yes, former example more async latter.
lets try picture following scenario: create library responsible talking third party service. expose method, lets call fooasync
, returns large list<foo>
. user knows api async, feels calling ui thread , not worrying blocking long duration.
now, lets see happeneds when makes call each method:
we execute
fooasync
, http request made, yielding control caller when reaching firstawait
. then, continues executing hitting secondawait
reads recieved stream, again yielding control caller until finishes. while, ui free process messages both major operations done async.we execute
fooasync
, make http request. yield control on firstawait
, good. then, receive response , read underlying stream synchronously. while read (and lets remember we're reading large stream) ui thread blocked on io operation, unable process other messages.
our second case undesired , worse, unexpected. told user he's receiving async
api, end blocking pretty long amount of time. not that, if task.result
called ui thread, may deadlock.
the benefit of using await
on both operations create truely async api, not wasting time on blocking io operations , not surprising calls method blocking.
i suggest reading best practices in asynchronous programming talks edge cases.
to conclude, if can go async "all way", so.
Comments
Post a Comment