c# - async await usages for CPU computing vs IO operation? -
i know async-await
keeps thread context , handle exception forwarding etc.(which helps lot).
but consider following example :
/*1*/ public async task<int> examplemethodasync() /*2*/ { /*3*/ var httpclient = new httpclient(); /*4*/ /*5*/ //start async task... /*6*/ task<string> contentstask = httpclient.getstringasync("http://msdn.microsoft.com"); /*7*/ /*8*/ //wait , return... /*9*/ string contents = await contentstask; /*10*/ /*11*/ //get length... /*12*/ int exampleint = contents.length; /*13*/ /*14*/ //return length... /*15*/ return exampleint; /*16*/ }
if async
method (httpclient.getstringasync
) io operation ( in sample above) - gain these things :
- caller thread not blocked
worker thread released because there io operation ( io completion ports...)(getstringasync usestaskcompletionsource
, not open new thread)- preserved thread context
- exception thrown back
but if instead of httpclient.getstringasync
(io operation) , have task of calcfirstmillionsdigitsof_pi_async
(heavy compute bound operation on sperate thread)
it seems things gain here :
- preserved thread context
- exception thrown back
- caller thread not blocked
but still have thread ( parallel thread) executes operation. , cpu switching between main thread , operation .
does diagnostics correct?
actually, second set of advantages in both cases. await
doesn't start asynchronous execution of anything, it's keyword compiler generate code handling completion, context etc.
you can find better explanation of in '"invoke method await"... ugh!' stephen toub.
it's asynchronous method decide how achieves asynchronous execution:
- some methods use task run code on threadpool thread,
- some use io-completion mechanism. there special threadpool that, can use tasks with custom taskscheduler
- some wrap taskcompletionsource on mechanism events or callbacks.
in every case, specific implementation releases thread (if 1 used). taskscheduler releases thread automatically when task finishes execution, functionality cases #1 , #2 anyway.
what happens in case #3 callbacks, depends on how callback made. of time callback made on thread managed external library. in case have process callback , return allow library reuse method.
edit
using decompiler, it's possible see getstringasync
uses third option: creates taskcompletionsource gets signalled when operation finishes. executing operation delegated httpmessagehandler.
Comments
Post a Comment