What are async and await in C#?
Understand asynchronous programming, non-blocking I/O, and how async and await work together in C#.
Answer
async and await are C# language features that make asynchronous code easier to write and read. They are commonly used for I/O-bound operations such as HTTP requests, database calls, and file access.
The async modifier allows a method to use await. The await expression asynchronously waits for an operation to complete without blocking the current thread while the operation is pending. When the operation completes, execution resumes after the await expression.
Async does not automatically mean that work runs on a new thread. For I/O-bound work, the underlying operation can make progress without occupying a thread for the entire wait. CPU-bound work requires a different approach and may use Task.Run where appropriate in client applications or carefully designed background workloads.
Code example
public async Task<string> GetPageTitleAsync(HttpClient httpClient, string url)
{
string html = await httpClient.GetStringAsync(url);
return ExtractTitle(html);
}Key points to remember
- Use async/await for asynchronous operations, especially I/O-bound work.
- Avoid async void except for event handlers; prefer Task or Task<T>.
- Avoid blocking asynchronous code with .Result or .Wait() when possible.
- Propagate cancellation tokens when APIs support cancellation.
Keep practising
Understanding beats memorization.
Explain the concept in your own words, then think through how you would use it in a real project.
AI-powered mock interview practice is planned for a future release.