Skip to content

Async and await in C#: tasks and async Main

Most of the time an OrdersPortal service spends handling a request is waiting: for a database, a pricing API, a file. Asynchronous code lets that waiting happen without holding a thread, so a server handles more requests and a desktop app stays responsive. This page covers the language support for it: async and await themselves, and the asynchronous Main entry point that lets console tools and workers use them from the first line.

Every complete sample is a file-based program: save it as sample.cs and run dotnet run sample.cs with the .NET 10 SDK (C# 14). All samples on this page were compiled and run with .NET SDK 10.0.115.

Feature Version Use it when
Async and await C# 5 Code waits on I/O such as HTTP, databases, files or queues.
Async Main C# 7.1 A console app or worker must await work during startup or as its main job.

Introduced in C# 5 (.NET Framework 4.5). Marking a method async lets it use await. When execution reaches await on an operation that has not finished, the method returns an incomplete Task to its caller and the rest of the method is registered as a continuation. No thread sits blocked while the I/O is in flight. When the operation completes, the method resumes, on the captured synchronization context if there is one (UI apps) or on a thread-pool thread otherwise (ASP.NET Core, console apps).

Return Task for no result, Task<T> for a result, and consider ValueTask<T> only for hot paths that usually complete synchronously. Exceptions thrown inside the method are stored in the task and rethrown at the await. To run independent operations concurrently, start them all first and then await Task.WhenAll(...); awaiting each one immediately runs them one after another. Pass a CancellationToken through every layer so callers can stop work they no longer need; cancelled operations throw OperationCanceledException.

var client = new OrderApiClient();
OrderSummary summary = await client.GetSummaryAsync(1001, CancellationToken.None);
Console.WriteLine($"Order {summary.OrderId}: {summary.InStock} in stock at {summary.UnitPrice:0.00}");
using var timeout = new CancellationTokenSource(TimeSpan.FromMilliseconds(50));
try
{
await client.GetSummaryAsync(1002, timeout.Token, slowPricing: true);
}
catch (OperationCanceledException)
{
Console.WriteLine("Order 1002: pricing service timed out, showing cached page");
}
record OrderSummary(int OrderId, int InStock, decimal UnitPrice);
class OrderApiClient
{
public async Task<OrderSummary> GetSummaryAsync(int orderId, CancellationToken ct, bool slowPricing = false)
{
// Start both calls before awaiting either, so they run concurrently.
Task<int> stockTask = GetStockAsync(orderId, ct);
Task<decimal> priceTask = GetPriceAsync(orderId, slowPricing ? 5_000 : 20, ct);
await Task.WhenAll(stockTask, priceTask);
return new OrderSummary(orderId, stockTask.Result, priceTask.Result);
}
private static async Task<int> GetStockAsync(int orderId, CancellationToken ct)
{
await Task.Delay(30, ct); // stands in for an HTTP or database call
return orderId % 7 + 3;
}
private static async Task<decimal> GetPriceAsync(int orderId, int delayMs, CancellationToken ct)
{
await Task.Delay(delayMs, ct);
return 19.99m;
}
}

Output:

Order 1001: 3 in stock at 19.99
Order 1002: pricing service timed out, showing cached page

Reading stockTask.Result after await Task.WhenAll is safe because both tasks have already completed; reading .Result before that would block.

Pitfalls:

  • async void. Exceptions from an async void method cannot be caught by the caller and can crash the process. Use it only for event handlers; everywhere else return Task.
  • Blocking on async code. .Result, .Wait() and GetAwaiter().GetResult() on an unfinished task waste a thread and can deadlock where a single-threaded synchronization context exists (classic ASP.NET, WinForms, WPF). Go “async all the way”.
  • async does not mean “runs on another thread”. CPU-bound work inside an async method still runs on the current thread until the first incomplete await; use Task.Run deliberately for CPU work in UI apps, not in ASP.NET Core request handlers.

Introduced in C# 7.1 (Visual Studio 2017 version 15.3). The program entry point can be async and return Task or Task<int>, with or without a string[] args parameter. Before C# 7.1, a console tool that needed async APIs had to block in Main with .GetAwaiter().GetResult(). The compiler now generates that bridge for you: it emits a synchronous entry point that waits on the task your Main returns, so the process stays alive until the work is finished.

Task<int> gives you a process exit code, which scripts, CI jobs and container orchestrators read to decide whether a run succeeded. With top-level statements (C# 9), using await in the top-level code produces an async entry point automatically, and return 2; sets the exit code; an explicit Main is still useful when you want a named class or several helper methods around it.

class Program
{
static async Task<int> Main(string[] args)
{
string[] orderFiles = args.Length > 0 ? args : ["orders-2026-11-17.csv", "orders-2026-11-18.csv"];
try
{
int total = 0;
foreach (string file in orderFiles)
{
total += await ImportAsync(file);
}
Console.WriteLine($"Imported {total} orders");
return 0; // process exit code
}
catch (InvalidDataException ex)
{
Console.Error.WriteLine($"Import failed: {ex.Message}");
return 2;
}
}
static async Task<int> ImportAsync(string file)
{
await Task.Delay(10); // stands in for reading the file
if (file.Contains("bad"))
throw new InvalidDataException($"{file} has a malformed header");
Console.WriteLine($" {file}: 120 rows");
return 120;
}
}

Output of dotnet run sample.cs (exit code 0):

orders-2026-11-17.csv: 120 rows
orders-2026-11-18.csv: 120 rows
Imported 240 orders

Output of dotnet run sample.cs -- orders-bad.csv (exit code 2):

Import failed: orders-bad.csv has a malformed header

Pitfalls:

  • async void Main is not an entry point. Only Task and Task<int> return types qualify.
  • Unhandled exceptions end the process. They propagate out of the generated entry point; catch the ones you can report and map them to exit codes.
  • Hosted apps already have one. In ASP.NET Core and the Generic Host, await app.RunAsync() is the async main loop; do not start a second one.
  • Library and service code: async methods returning Task or Task<T>, with a CancellationToken parameter.
  • Console tools and batch jobs: async Main (or top-level statements with await) returning Task<int> so failures reach the caller as an exit code.
  • Disposing async resources such as streams and database connections: await using, covered in Resource management.

What does the compiler do with an async method? It rewrites the method into a state machine. Each await on an incomplete operation saves local state, returns to the caller, and registers a continuation that resumes the state machine when the awaited operation completes.

Why is async void dangerous? The caller gets no Task, so it cannot await completion or observe exceptions. An exception escapes to the synchronization context or thread pool and typically crashes the process. It exists for event handlers.

What is the difference between await Task.WhenAll(a, b) and await a; await b;? If both tasks were already started, both forms wait for both, but WhenAll makes the concurrency explicit and surfaces all exceptions on the returned task (the await rethrows the first). If the tasks are created at the await sites, the second form runs them sequentially.

When would you use ConfigureAwait(false)? In general-purpose library code that does not need to resume on a UI or legacy ASP.NET context. It avoids a context hop and protects callers who block on the task. ASP.NET Core has no synchronization context, so application code there rarely needs it.

How does an async Main keep the process alive? The compiler generates a synchronous entry point that calls your Main and waits for the returned task, so the process exits only when the task completes, with the int result as the exit code.

Senior scenario: OrdersPortal’s checkout endpoint calls inventory, pricing and fraud APIs one after another and p99 latency is too high. What do you change? Start the three independent calls together and await Task.WhenAll, so latency becomes the slowest call rather than the sum. Add a per-call timeout through a linked CancellationTokenSource and decide per dependency what happens on timeout (fail the checkout for fraud, fall back to cached prices for pricing). Make sure nothing in the path blocks with .Result, and use the typed HttpClient from IHttpClientFactory so connection reuse is handled.