c# - Asp.Net WebApi run MongoDB query/save async -
i trying figure out when use task.run , when not.
in project i'm using webapi combined mongodb store account information.
so following sample code, better of using submit or sumbitasync method client call?
public class testcontroller : apicontroller { [httppost] public void submit() { dosave(); } public async task submitasync() { await task.run(() => dosave()); } private void dosave() { mymongodbcollection.save(new testentity()); } }
the mongodb c# driver not support async methods.
there's no point in using task.run
here.
the point of using async i/o in asp.net free thread, can handle other requests, until i/o has completed. meanwhile, no thread blocked. when i/o operation has finished, i/o completion port signaled , method resume.
using task.run
, you're deferring threadpool thread, , making that thread block waiting i/o.
in other words, if client doesn't support async i/o, 1 of threads block. might synchronously , avoid unnecessary context switches.
from stephen cleary's blog post "task.run etiquette examples: don't use task.run in implementation":
there (at least) 4 efficiency problems introduced use await task.run in asp.net:
extra (unnecessary) thread switching task.run thread pool thread. similarly, when thread finishes request, has enter request context (which not actual thread switch have overhead).
extra (unnecessary) garbage created. asynchronous programming tradeoff: increased responsiveness @ expense of higher memory usage. in case, end creating more garbage asynchronous operations totally unnecessary.
the asp.net thread pool heuristics thrown off task.run "unexpectedly" borrowing thread pool thread. don't have lot of experience here, gut instinct tells me heuristics should recover if unexpected task short , not handle elegantly if unexpected task lasts more 2 seconds.
asp.net not able terminate request early, i.e., if client disconnects or request times out. in synchronous case, asp.net knew request thread , abort it. in asynchronous case, asp.net not aware secondary thread pool thread "for" request. possible fix using cancellation tokens, that's outside scope of blog post.
Comments
Post a Comment