Many articles (e.g. this one) say the advantage of async methods in ASP.NET (MVC) is that they allow release of threads to the thread pool which allow other requests to be serviced. If async methods do not use thread pool threads, where do they execute and why?
1 Answer
The main use of async in this context is to wait for external resources - for example, databases (sql or no-sql), web APIs (http), etc. There is no thread required for these, since they are not CPU-based operations. The work is resumed at some point after the data becomes available. Consider:
var cust = await someApi.GetCustomerAsync();
var account = await anotherApi.GetAccount(cust.AccountId);
return View(account);
The await here represent out-of-process work - typically network. They don't "run" anywhere, because they are not CPU operations. When the place-holder tasks report completion, then the next part of the method can resume, typically via the captured sync-context.
5 Comments
Ehsan Sajjad
any tutorial or good post link where i can study it how to use it in mvc application
Thanks Marc, upvoted and accepted as answer. I find this unintuitive because the way I see it is still managed code that must run somewhere, i.e. opening up a database connection etc. but your answer together with article provided by @SriramSakthivel will probably convince me otherwise! :)
Marc Gravell
@martijn_himself but what is "running" at that point? sure, there are async IO things in place at the socket level, but those are callback-based, typically
@MarcGravell Ah, I see, that makes sense! I am starting to think I and perhaps others struggle with these concepts because I don't have a computer science background and have very little experience with unmanaged code/ hardware etc. This has made me think on more than one occasion it was not such a good idea to get into software development :).