C# Interview Question #62
What are async and await in C#?
Async/Await, Tasks & Multithreading Mid-Level Intermediate
Quick Interview Answer
The async modifier allows a method to use await and normally indicates that the method returns Task, Task<T>, ValueTask, or ValueTask<T>. The await operator asynchronously waits for an awaitable operation to complete.
Detailed Explanation
The async modifier allows a method to use await and normally indicates that the method returns Task, Task<T>, ValueTask, or ValueTask<T>. The await operator asynchronously waits for an awaitable operation to complete.
When an incomplete task is awaited, control can return to the caller instead of blocking the current thread. When the operation completes, execution continues from the point after await.
An async method should normally be asynchronous all the way through its call chain instead of blocking with .Result or .Wait().
Code Example
public async Task<string> GetDataAsync()
{
using HttpClient client = new();
string data = await client.GetStringAsync("https://example.com");
return data;
}