Explain how does Asynchronous tasks (Async/Await) work in .NET?

Technology CommunityCategory: .NET CoreExplain how does Asynchronous tasks (Async/Await) work in .NET?
VietMX Staff asked 3 years ago
Problem

Consider:

private async Task<bool> TestFunction()
{
  var x = await DoesSomethingExists();
  var y = await DoesSomethingElseExists();
  return y;
}

Does the second await statement get executed right away or after the first await returns?

await pauses the method until the operation completes. So the second await would get executed after the first await returns.

The purpose of await is that it will return the current thread to the thread pool while the awaited operation runs off and does whatever.

This is particularly useful in high-performance environments, say a web server, where a given request is processed on a given thread from the overall thread pool. If we don’t await, then the given thread processing the request (and all it’s resources) remains “in use” while the db / service call completes. This might take a couple of seconds or more especially for external service calls.