I'm trying to fully understand async
-await
and one of the gaps in my understanding is seeing what is "All the Way Down." I create an async
method, it is called by another async
method, etc., all the way down to something that I understand in vague terms like "a UI" or "a web server that can handle multiple requests". How would I describe in technical terms what is "all the way down"?
So let's take the second example of a web server. Say I have a controller action like
[HttpGet]
public async Task<IHttpActionResult> GetRecords()
{
var records = await repository.GetRecordsFromDbAsync();
return Ok(records);
}
Where can I find in the .NET source code the "all the way down" code that enables this to be called asynchronously?
An async method runs synchronously until it reaches its first await expression, at which point the method is suspended until the awaited task is complete. In the meantime, control returns to the caller of the method, as the example in the next section shows.
In order to run multiple async/await calls in parallel, all we need to do is add the calls to an array, and then pass that array as an argument to Promise. all() . Promise.
Async functions The word “async” before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically. So, async ensures that the function returns a promise, and wraps non-promises in it.
In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously. Code after each await expression can be thought of as existing in a .then callback.
The phrase "async all the way down" is a bit misleading, because it usually refers to the fact that once you use an async method, you need to have async methods all the way up (or back, depending on your mental image) - from your async method to its caller, and then your caller's caller, and so forth, all the way back.
Your example shows a WebApi/MVC controller that exposes an async
task. The next step in the async
chain is the WebApi/MVC infrastructure that receives the HTTP GET request, maps it to a controller, and dispatches the call to the controller's method. This infrastructure is async
aware, meaning it knows to call async
controller methods properly and await
their result to return the HTTP response.
As to how exactly that infrastructure is implemented, I don't specifically know, nor care - I know that ASP.NET web services support async Task
controllers, and that's good enough for me.
All the way down would be the Win32 API. At that level, async I/O is done via OVERLAPPED
objects, and alertable waits such as WaitForMultipleObjectsEx
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With