What does it mean?
Asynchronous actions allow developers to handle more concurrent requests and can be implemented using async / await keywords.
Asynchronous actions are useful in scenarios where we are performing some network operation such as calling a remote service, webapi etc.
What are the Benefits?
1) It can make application to handle more users.
2) It can process multiple I/O bound methods in parallel
3) It can make UI interface more responsive to the user
4) It can perform complex database calls that take seconds to return.
How to Implement?
We can implement asynchronous actions using “async / await” keywords. Below is the sample
public class DbHelper { public async Task { SampleEntities db = new SampleEntities (); var query = from c in db.Companies orderby c.CompanyId ascending select c; List return data; } } |
---|
public async Task { DbHelper helper = new DbHelper(); List return View(data); } |
---|
Execution of Synchronous Actions:
When a request calls to the particular action, ASP.NET initializes a thread from thread pool and runs that action method on the allocated thread.
As the action is synchronous, all the operations, including the remote service call, occur sequentially (one after the other).
Once all the operations are done, the thread running the code can be reused for later execution. Thus allocated thread from the pool is blocked during the entire execution i.e. from start to end.
Execution of Ansynchronous Actions:
When a request calls to the particular action, ASP.NET initializes a thread from thread pool and runs that action method on the allocated thread like synchronous but entire thread should not block and executes another request asynchronouslyand immediately return to thread pool as soon as it executed to perform other thread pool requests.
Using above methods the total time of execution is almost similar but performance can be achieved by queuing less no of requests in asynchronous model i.e. by managing concurrent requests.
Where to Use?
1) Complex Database calls
2) Web services, Web API and other external 3rd party API.
Summary:
So we have learned that what is, when to use, how to implement and what are the advantages and handling asynchronous requests in MVC.
Thanks for reading.