c# - ASP.NET async task execution sequence -
i come across concurrency coding on asp.net , found there 2 ways trigger async method @ page_load method
- registerasynctask(new pageasynctask(dosthasync()));
- await dosthasync();
however, have different operation result. case 1, code right after registerasynctask run before code in dosthasync(). while code after await run @ completion of dosthasync().
e.g:
//protected async void page_load(object sender, eventargs e) protected void page_load(object sender, eventargs e) { response.write("start</br>"); response.flush(); registerasynctask(new pageasynctask(dosthasync())); //await dosthasync(); response.write("end</br>"); response.flush(); } public async task loadsomedata() { await task.delay(1000); response.write("do sth async</br>"); response.flush(); }
this code snippet generate following result:
start end sth async *(after 1 second delay)*
while uncomment await dosthasync() code , comment registerasynctask, following result shown.
start sth async *(after 1 second delay)* end
in rick anderson's article using asynchronous methods in asp.net 4.5, suggested using registerasynctask give better control on code execution. however, gives unexpected result i'm looking while await in page_load generate identical 1 try similar code sequence in windows program.
in article, rick has code of stopwatch start before getpwgsrvasync() fired , stop after async code completed showing how long code executed. shows elapsed time 0.872s in screen cap. therefore it's expected stopwatch stopped after previous code including in async method completed.
....... stopwatch stopwatch = new stopwatch(); stopwatch.start(); registerasynctask(new pageasynctask(dosthasync())); //await dosthasync(); stopwatch.stop(); response.write(string.format("elapsed time:{0}",stopwatch.elapsed.milliseconds / 1000.0)); response.write("</br>"); response.flush(); .......
while follow same way code snippet above, have different result in either registerasynctask or await dosthasync(). although elapsed time displayed @ different position, both give me short elapsed time 0.010s or 10+ms , it's believe stopwatch stopped shortly after async function dosthasync() fired. in fact, similar result in window program too, stopped soon.
after long description of problem, ask way of async coding have better control , code pattern. in between, how can have expected result of stopwatch give me exact code elapsed time.
page async tasks have been around since long before async-await
.
page async tasks executing asynchronous tasks (not task
s) in request lifecycle.
async-await
having asynchronous methods asynchronous operations.
if use async-await
in page_load
, because void
-returning method, runtime has no way know method asynchronous , if asynchronous work done or not.
have @ the documentation pageasynctask
, see best suits needs. should have serious @ page async tasks.
Comments
Post a Comment