An async function is a function that allows for asynchronous programming. It enables non-blocking execution, meaning the program can continue running while waiting for tasks like network requests or file operations to complete.
- The async keyword turns a method into an async method, which allows you to use the await keyword in its body.
- When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete.
- await can only be used inside an async method.
private readonly HttpClient _httpClient = new HttpClient();
[HttpGet, Route("DotNetCount")]
public async Task<int> GetDotNetCount()
{
// Suspends GetDotNetCount() to allow the caller (the web server)
// to accept another request, rather than blocking on this one.
var html = await _httpClient.GetStringAsync("https://dotnetfoundation.org");
return Regex.Matches(html, @"\.NET").Count;
}
Below is the quite clear and concise explanation:
//this is pseudocode
async Method()
{
code;
code;
await something;
moreCode;
}
When Method is invoked, it executes its contents (code; lines) up to await something;. At that point, something; is fired and the method ends like a return; was there.
something; does what it needs to and then returns.
When something; returns, execution gets back to Method and proceeds from the await onward, executing moreCode;
In a even more schematic fashion, here's what happens:
- Method is invoked
code;is executedsomething;is executed, flow goes back to the point whereMethodwas invoked- execution goes on with what comes after the
Methodinvocation - when
something;returns, flow returns insideMethod moreCode;is executed andMethoditself ends (yes, there could be something elseawait-ing on it too, and so on and so forth)
Reference: https://docs.microsoft.com
0 comments:
Post a Comment