What does await mean
The keyword await
serves to make asynchronous calls, so that if the method being called is slow, all that comes after the call using await
is suspended, waiting to be executed in a queue.
For example:
código parte 1;
await FazerAlgoQuePodeDemorar();
código parte 2;
If the function called FazerAlgoQuePodeDemorar
in its internal implementation will take time, it will interrupt itself, leaving the código-parte-2
suspended, waiting to be executed after the completion of the internal processing of the called function using await
.
And in the context of the MVC?
A MVC action that is defined as async
, allows a method within it to be called with await
, causing MVC to not occupy the request queue that is processed by the server until the method called with await
finish, and finally return a result.
This was done because each time a non-synchronistic action is called, it occupies a thread that is available to process requests, and there is a limit to the number of threads that do this work. Using async
, request processing thread is released to process other requests, while a call made with await
takes care of the request processing done previously in another plan.
This is only really useful, for actions that make I/O calls, such as database access, requests to external servers, hard drive recordings, and other tasks that can be done asynchronously.
References
MSDN: Using an asynchronous controller in ASP.NET MVC
In this topic of MSDN, has a very explanatory image of what happens, basically everything that comes after the call using await
in the asynchronous action, it is transferred to another thread, other than the one of the pool that meets requests, thus leaving it free to meet other requests.
This blog, in English, explains exactly the asynchronous action calls, using async
and why its use makes the server capable of meeting more requests simultaneously.
The best explanation for asynchronous methods
– Guilherme Almeida
It would only be used in I/O method?
– DanOver
@Danover is usually the most suitable, it is difficult to find a situation that is useful and does not have IO.
– Maniero