Understanding Async/Await in C#
Ad
Async/Await in C#
C#'s async/await lets you write non-blocking code that stays readable. It's based on the Task type.
Basic Example
async Task<string> GetDataAsync() {
using var client = new HttpClient();
string result = await client.GetStringAsync("https://api.com");
return result;
}
Key Rules
- Mark the method
asyncand returnTaskorTask<T>. awaitunwraps the Task result without blocking the thread.- Avoid
async voidexcept for event handlers.
Running in Parallel
var t1 = GetUserAsync();
var t2 = GetOrdersAsync();
await Task.WhenAll(t1, t2); // both run concurrently
FAQs
Why not just use threads?
Async frees the thread while waiting on I/O, scaling far better. More in our C# guides.
What is ConfigureAwait(false)?
It avoids capturing the sync context — useful in libraries for performance.
