Tech News, Tech & Coding · Free Online Tools

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

Understanding Async/Await in C#

C#By Muhammad Fareed
c-sharpunderstandingasyncawait

Short answer: async and await let C# code wait for slow operations (network, files, databases) without blocking a thread. An async method returns a Task; await pauses the method until the task finishes and then continues, while the thread is free to do other work.

Why asynchronous code?

A blocked thread cannot serve other requests or keep a UI responsive. In a web server, blocking threads on I/O limits how many users you can handle; in a desktop or mobile app, it freezes the interface. Async code frees the thread while waiting.

A simple example

using System.Net.Http;

var client = new HttpClient();

async Task<string> GetPageAsync(string url)
{
    string html = await client.GetStringAsync(url);
    return html;
}

string page = await GetPageAsync("https://example.com");
Console.WriteLine(page.Length);
  • The method is marked async and returns Task<string>.
  • await yields control until the download completes.
  • By convention, async method names end with Async.

Return types

Return typeUse
TaskAn async method that returns nothing
Task<T>An async method that returns a value of type T
ValueTask / ValueTask<T>Performance optimization when results are often available synchronously
voidOnly for event handlers; avoid elsewhere

Running tasks in parallel

// Sequential: total time = a + b
var a = await GetAAsync();
var b = await GetBAsync();

// Concurrent: total time = max(a, b)
var taskA = GetAAsync();
var taskB = GetBAsync();
var results = await Task.WhenAll(taskA, taskB);

Start the tasks first, then await them together. Use Task.WhenAny to continue when the first one finishes (for timeouts).

Error handling

try
{
    var data = await GetPageAsync("https://example.com/missing");
}
catch (HttpRequestException ex)
{
    Console.WriteLine("Request failed: " + ex.Message);
}
finally
{
    Console.WriteLine("Done");
}

Exceptions thrown inside an async method are stored in the returned task and rethrown at the await, so normal try/catch works. With Task.WhenAll, await rethrows the first exception; inspect the task's Exception to see all.

Cancellation

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));

try
{
    var text = await client.GetStringAsync("https://example.com", cts.Token);
}
catch (OperationCanceledException)
{
    Console.WriteLine("Timed out or cancelled");
}

Accept a CancellationToken parameter in your own async methods and pass it down. In ASP.NET Core, a token tied to the HTTP request is available so work stops when the client disconnects.

Async in ASP.NET Core and UI apps

[HttpGet("{id}")]
public async Task<ActionResult<Product>> Get(int id, CancellationToken ct)
{
    var product = await _db.Products.FindAsync(new object[] { id }, ct);
    return product is null ? NotFound() : Ok(product);
}

Make the whole call chain async ("async all the way"). See ASP.NET Core MVC and Entity Framework Core.

Common mistakes

  • Blocking on async code with .Result or .Wait(). This can cause deadlocks in UI and older ASP.NET contexts and wastes threads. Use await.
  • async void methods: exceptions cannot be caught by the caller and can crash the app. Return Task instead, except for event handlers.
  • Forgetting to await a task, so it runs unobserved and errors are lost.
  • Using Task.Run to "make I/O async" on a server. It just moves work to another thread; use truly async APIs.
  • Awaiting inside a loop when the operations are independent; start them all and use Task.WhenAll.

Async vs multithreading

Async is mostly about waiting efficiently, not about running code on multiple threads. For CPU-heavy work, use Task.Run (to keep a UI responsive) or Parallel classes to use several cores.

Related concepts

The same idea exists in JavaScript with promises; compare with async/await in JavaScript. Async methods work with LINQ and with collections via IAsyncEnumerable and await foreach. New to C#? See what C# is.

FAQs

Does await create a new thread?

No. It releases the current thread while waiting. Continuation may run on the same or another thread depending on the context.

What is a Task?

An object that represents an ongoing operation and its eventual result or failure.

Can I make a constructor async?

No. Use an async factory method, for example static async Task<MyClass> CreateAsync().

What does ConfigureAwait(false) do?

It tells the runtime not to resume on the original context. It is commonly used in library code; ASP.NET Core has no synchronization context, so it matters less there.