-1

This question might seem duplicate, but I have done enough reading and still couldn't find answer to my question.

Lets imagine I have some pseudo code like this.

[HttpGet("someendpoint")]
public Task<IActionResult> DoSomethingAsync()
{
   await DoSomethingPrivateAsync();
}

private Task DoSomethingPrivateAsync()
{
   await ADONETExecuteReaderAsync();
}

What happens when someendpoint is hit. I understand when await is encountered, control is returned to the caller. But who runs the code inside DoSomethingPrivateAsync?

Also, assuming this Web API is hosted on Kestrel or any webserver, what happens when control returns back upon hitting await?

My above example above is very simple, but I am trying to understand in a broader perspective. For example, if there is long chain of await's (with some IO operations in between), how does the execution happen?

  • See the excellent articles series https://weblogs.asp.net/dixin/understanding-c-sharp-async-await-1-compilation. – Chayim Friedman Sep 23 '18 at 08:52
  • It is frustrating to see how this question was marked as duplicate where in fact it is not. The linked question was what I came up in the google results and IT DID NOT answer the question. (sigh..) – user7368874 Sep 23 '18 at 09:21

1 Answers1

0

When you do an I/O bound operation as fully async basically this steps happens:

  1. Request thread calls async I/O method and awaits for it this means the request handler thread can process another request while first request operates on I/O

  2. A Task created for I/O operation

  3. One of the thread pool threads handles the task

  4. On the I/O side, thread does not blocks, now the job works on I/O like disk or network. We give a file descriptor the OS and say "hey os do this job with this descriptor and call me back when it finish or any data changes"

  5. When job is done OS calls us back

So with this way request handles as async we don't block any thread.

I rocemmend you to read blog posts of Stephen Cleary :

https://blog.stephencleary.com/2013/11/there-is-no-thread.html

https://blog.stephencleary.com/2012/02/async-and-await.html

https://blog.stephencleary.com/2016/12/eliding-async-await.html

Emre Savcı
  • 3,034
  • 2
  • 16
  • 25