Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to C#
Understanding Async/Await in C#

Understanding Async/Await in C#

C#2,304 viewsBy Admin
c-sharpunderstandingasyncawait

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 async and return Task or Task<T>.
  • await unwraps the Task result without blocking the thread.
  • Avoid async void except 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.