What do the 'async' and 'await' keywords do, and how do they relate to each other?
Short answer
'async' marks a method as containing asynchronous operations, enabling the use of 'await' inside it; 'await' pauses the method's execution (without blocking the calling thread) until the awaited Task completes, then resumes execution with the result.
Advertisement
AModel answer
'async' marks a method as containing asynchronous operations, enabling the use of 'await' inside it; 'await' pauses the method's execution (without blocking the calling thread) until the awaited Task completes, then resumes execution with the result.
async Task<string> FetchDataAsync() {
HttpClient client = new HttpClient();
string result = await client.GetStringAsync("https://api.example.com/data");
return result;
}Real-world example
Fetching data from a web API or database without blocking the UI thread or a server's request-handling thread.
Likely follow-ups
- What does an async method's method signature typically return, and why not just 'void'?
Related topics