C# · Lesson 6

Async/await and Tasks

Task and Task<T>, what await really does, running work concurrently with WhenAll and WhenAny, cancellation and timeouts, IAsyncEnumerable and Channel<T>, ConfigureAwait and the sync-over-async deadlock, compared with JavaScript promises and F# async.

13 min read

In short

  • Task<T> is Promise<T>, and tasks are hot
  • Code after await may run on another thread
  • await in a loop is sequential; Task.WhenAll overlaps
  • Take a CancellationToken and pass it on
  • Never .Result, .Wait() or async void

Almost every method in a .NET backend is async: EF Core queries, HttpClient calls, message queues, object storage, document databases. The syntax will feel familiar from TypeScript: async, await, and Task<T> where you'd write Promise<T>. The model underneath differs in one important way. .NET has a thread pool, so your code can run on several threads at once, and the code after an await may continue on a different thread from the code before it. Most of the time you won't notice. When you do, it's usually a race condition, a deadlock or a server that has run out of threads.

This lesson builds the right mental model, then the exercises turn it into the tools you'll use at work. The lab runs C# snippets as programs with top-level statements, so await works directly in every ▶ Try block.

Task is .NET's Promise

▶ Try
Task<int> answer = Task.FromResult(42); // already completed, like Promise.resolve(42)
Task delay = Task.Delay(100);           // completes after about 100 ms

Console.WriteLine(answer.IsCompleted);  // True
Console.WriteLine(delay.IsCompleted);   // False
await delay;
Console.WriteLine(delay.IsCompleted);   // True
Console.WriteLine(await answer);        // 42
TypeScriptC#
Promise<T> / Promise<void>Task<T> / Task
Promise.resolve(x) / Promise.reject(e)Task.FromResult(x) / Task.FromException<T>(e)
new Promise((resolve, reject) => ...)TaskCompletionSource<T> with SetResult / SetException
a setTimeout promiseTask.Delay(ms)
Promise.allTask.WhenAll
Promise.raceTask.WhenAny (returns the first task to finish)
AbortController / AbortSignalCancellationTokenSource / CancellationToken
async function* and for awaitIAsyncEnumerable<T> and await foreach

Like promises, tasks are hot: calling an async method starts the work, and the Task you get back represents work that's already running. You'll also meet ValueTask<T>, a cheaper variant for methods that usually finish synchronously (a cache hit, a buffered read). Await a ValueTask exactly once and never read .Result before it completes. Most of the time it appears in framework signatures (DisposeAsync, ChannelReader.ReadAsync), and you just await it.

What await really does

▶ Try
Console.WriteLine("1 before the call");
var task = LoadAsync();
Console.WriteLine("3 the caller continues");
var value = await task;
Console.WriteLine($"5 got {value}");

static async Task<int> LoadAsync()
{
    Console.WriteLine("2 runs synchronously until the first await");
    await Task.Delay(50);
    Console.WriteLine("4 the continuation");
    return 42;
}
  1. An async method runs synchronously until it awaits a task that isn't finished yet. Then it returns an incomplete Task to its caller.
  2. The compiler rewrites the method into a state machine: a struct whose MoveNext() method holds your code cut into pieces at each await. Local variables become fields so they survive between pieces.
  3. When the awaited task completes, it calls MoveNext() again, which jumps to the right piece and carries on.
  4. Where the rest runs depends on the SynchronizationContext. A UI app (WPF, WinForms, MAUI) posts it back to the UI thread. ASP.NET Core, console apps and worker services have no context, so it runs on whichever thread-pool thread is free.
▶ Try
Console.WriteLine($"before: thread {Environment.CurrentManagedThreadId}");
await Task.Delay(10);
Console.WriteLine($"after:  thread {Environment.CurrentManagedThreadId} (often a different one)");

Awaiting a finished task doesn't pause

This is the biggest surprise for a JavaScript developer. If the task has already completed, await just takes the result and keeps going. Nothing is queued.

▶ Try
Console.WriteLine("A");
var t = GetCachedAsync();
Console.WriteLine("D");
await t;

static async Task GetCachedAsync()
{
    Console.WriteLine("B");
    await Task.CompletedTask; // already complete: no pause
    Console.WriteLine("C");
}
// A B C D

The same shape in TypeScript prints A B D C, because await always queues a microtask:

▶ Try
console.log('A');
const t = (async () => {
  console.log('B');
  await undefined;
  console.log('C');
})();
console.log('D');

That's why a cached ValueTask is cheap, and why an async method can finish before it even returns. When you really need to give the caller its turn first, await Task.Yield() forces a real pause.

Exceptions live inside the task

An exception thrown inside an async method doesn't fly out of the call. It's stored in the task (the task is faulted), and await rethrows it, as the original exception type.

▶ Try
var task = ChargeAsync(-5m);           // nothing thrown here...
Console.WriteLine(task.Status);       // Faulted: even the argument check ended up in the task
try
{
    await task;                        // ...it's rethrown here
}
catch (ArgumentOutOfRangeException e)
{
    Console.WriteLine($"caught: {e.ParamName}");
}

static async Task<decimal> ChargeAsync(decimal amount)
{
    if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));
    await Task.Delay(10);
    return amount;
}
  • await throws the first exception. .Wait() and .Result wrap everything in an AggregateException, one more reason to avoid them.
  • When several tasks in a Task.WhenAll fail, await throws just one of them (which one depends on the .NET version and the overload, so don't rely on it). The Task returned by WhenAll has all of them in task.Exception.InnerExceptions.
  • async void methods have no task to store the exception in. It's rethrown on the thread pool and crashes the process. Only use async void for UI event handlers. Watch out for async lambdas passed where an Action is expected: items.ForEach(async x => await SaveAsync(x)) is async void in disguise. It also doesn't wait for anything.

Running work concurrently

▶ Try
using System.Diagnostics;

var sw = Stopwatch.StartNew();
foreach (var id in new[] { 1, 2, 3 }) await GetUserAsync(id);
Console.WriteLine($"one at a time: about {Round(sw.ElapsedMilliseconds)} ms");

sw.Restart();
var users = await Task.WhenAll(new[] { 1, 2, 3 }.Select(GetUserAsync));
Console.WriteLine($"all at once:   about {Round(sw.ElapsedMilliseconds)} ms, got {string.Join(", ", users)}");

static async Task<string> GetUserAsync(int id)
{
    await Task.Delay(100);
    return $"user {id}";
}

static long Round(long ms) => (long)Math.Round(ms / 100.0) * 100;
  • await in a loop is sequential. Use it when each step needs the previous result, or when the other side can't take parallel calls.
  • Task.WhenAll(tasks) waits for all of them, and its results come back in input order, whatever order they finished in. Select is lazy: WhenAll enumerates it, which starts all three calls, and only then waits.
  • Task.WhenAny(tasks) completes when the first task finishes (successfully or not) and returns that task. await it to get its result or exception. It's the building block for timeouts and hedged requests.
  • Don't start 10,000 calls at once. Limit concurrency with Parallel.ForEachAsync and MaxDegreeOfParallelism, a SemaphoreSlim, or a Channel<T> with a fixed number of workers (below).

Threads mean real races

In JavaScript, two callbacks never run at the same time. In .NET they do, so shared mutable state needs protection:

▶ Try
var unsafeCount = 0;
var safeCount = 0;
await Task.WhenAll(Enumerable.Range(0, 4).Select(_ => Task.Run(() =>
{
    for (var i = 0; i < 1_000_000; i++)
    {
        unsafeCount++;                        // read, add, write: two threads can interleave
        Interlocked.Increment(ref safeCount); // atomic
    }
})));
Console.WriteLine($"unsafe: {unsafeCount}, safe: {safeCount}"); // on a multi-core machine, unsafe is usually below 4000000

Use Interlocked for counters, lock for short critical sections, and ConcurrentDictionary or ConcurrentQueue for shared collections. A lock block can't contain await. For async code that needs mutual exclusion, use SemaphoreSlim(1, 1) with await semaphore.WaitAsync() and Release() in a finally.

Cancellation and timeouts

.NET's version of AbortSignal is the CancellationToken. A CancellationTokenSource owns it and decides when to cancel. The convention: every async method that does I/O takes a CancellationToken as its last parameter and passes it on to everything it calls.

▶ Try
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); // cancels itself after 100 ms
try
{
    await ImportAsync(cts.Token);
}
catch (OperationCanceledException)
{
    Console.WriteLine("import cancelled");
}

static async Task ImportAsync(CancellationToken cancellationToken)
{
    for (var batch = 1; ; batch++)
    {
        cancellationToken.ThrowIfCancellationRequested();
        Console.WriteLine($"batch {batch}");
        await Task.Delay(40, cancellationToken); // the delay itself stops early when cancelled
    }
}
  • Cancellation is cooperative. The token is a flag plus callbacks, and nothing stops code that never looks at it.
  • Cancelled work throws OperationCanceledException. Task.Delay and HttpClient throw its subclass TaskCanceledException, so catch the base type.
  • Who cancelled? HttpClient throws TaskCanceledException when its own Timeout expires, too. Use an exception filter to tell "we were asked to stop" apart from "something inside timed out": catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested).
  • Timeouts: cts.CancelAfter(TimeSpan.FromSeconds(5)). To combine a timeout with a caller's token, use CancellationTokenSource.CreateLinkedTokenSource(callerToken) and call CancelAfter on the linked source. task.WaitAsync(timeout, token) (.NET 6+) stops waiting, but doesn't stop the work itself.
  • Dispose CancellationTokenSources you create (using var cts = ...), because CancelAfter uses a timer.
TypeScriptC#
new AbortController()new CancellationTokenSource()
controller.signalcts.Token
controller.abort()cts.Cancel()
signal.throwIfAborted()token.ThrowIfCancellationRequested()
AbortSignal.timeout(ms)new CancellationTokenSource(TimeSpan.FromMilliseconds(ms))
AbortSignal.any([a, b])CancellationTokenSource.CreateLinkedTokenSource(a, b)

In ASP.NET Core, a CancellationToken parameter on an endpoint is the request's RequestAborted token: it fires when the client disconnects. A BackgroundService gets a stoppingToken that fires on shutdown.

ConfigureAwait and the classic deadlock

By default, await captures the current SynchronizationContext and resumes on it. In a UI app that's the UI thread. Now block that thread on the task:

// WPF (not runnable here)
private void LoadButton_Click(object sender, RoutedEventArgs e)
{
    var json = LoadAsync().Result; // 1. blocks the UI thread until LoadAsync finishes...
    Output.Text = json;
}

private async Task<string> LoadAsync()
{
    var json = await _http.GetStringAsync("https://example.com/api/orders");
    return json;                   // 2. ...but this line must run on the UI thread, which is blocked: deadlock
}

Classic ASP.NET (System.Web) had the same kind of context, which is where most "async deadlock" Stack Overflow answers come from.

  • ConfigureAwait(false) means "don't come back to the captured context, any thread is fine". Library code (NuGet packages, shared company libraries) puts it on every await, because it can't know whether a caller has a context or blocks on the result.
  • ASP.NET Core has no SynchronizationContext, so it can't deadlock this way, and app code there doesn't need ConfigureAwait(false). You'll still see it in older code and libraries. It's harmless.
  • .Result and .Wait() are still bad in ASP.NET Core. Each one blocks a thread-pool thread for the whole wait. Under load the pool runs out of threads (thread-pool starvation): requests queue up, latency explodes and health checks time out, while the CPU sits idle. The rule is async all the way down. If you truly must block, for example in an old synchronous Main, use .GetAwaiter().GetResult(), which at least throws the real exception instead of an AggregateException.

IAsyncEnumerable: async streams

▶ Try
using System.Runtime.CompilerServices;

await foreach (var page in FetchPagesAsync(3))
{
    Console.WriteLine($"processing {page}");
    if (page == "page 2") break;   // stop early: page 3 is never fetched
}

static async IAsyncEnumerable<string> FetchPagesAsync(
    int count, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
    try
    {
        for (var i = 1; i <= count; i++)
        {
            await Task.Delay(20, cancellationToken);
            Console.WriteLine($"fetched page {i}");
            yield return $"page {i}";
        }
    }
    finally
    {
        Console.WriteLine("producer cleaned up");
    }
}
  • It's pull-based: the producer runs only when the consumer asks for the next item. Breaking out of await foreach disposes the enumerator, which runs the producer's finally blocks.
  • [EnumeratorCancellation] connects a token passed through source.WithCancellation(token) to the iterator's parameter.
  • You'll use it with the paged list and query APIs of the cloud SDKs (the AWS, Azure and Google Cloud .NET SDKs all expose pages as an IAsyncEnumerable<T>, so await foreach walks every page for you) and with EF Core's AsAsyncEnumerable(). ASP.NET Core can also stream an IAsyncEnumerable<T> result as a JSON array.
  • It's the C# twin of TypeScript's async function* and for await (see the Advanced async TypeScript topic).

Channel<T>: producer/consumer queues

System.Threading.Channels gives you a fast, thread-safe async queue. A bounded channel makes a fast producer wait for a slow consumer: that's backpressure.

▶ Try
using System.Threading.Channels;

var channel = Channel.CreateBounded<int>(new BoundedChannelOptions(2) { FullMode = BoundedChannelFullMode.Wait });

var producer = Task.Run(async () =>
{
    for (var i = 1; i <= 5; i++)
    {
        await channel.Writer.WriteAsync(i); // waits while the channel is full
        Console.WriteLine($"produced {i}");
    }
    channel.Writer.Complete();              // no more items: ends ReadAllAsync below
});

await foreach (var item in channel.Reader.ReadAllAsync())
{
    await Task.Delay(30);                   // a slow consumer
    Console.WriteLine($"consumed {item}");
}
await producer;
  • Several consumers can read from the same channel: start N tasks that each run the await foreach. Each item goes to exactly one of them. That's a worker pool with a fixed concurrency.
  • Writer.Complete(exception) ends the stream with an error that readers see.
  • At work: an API endpoint that accepts a job quickly and hands it to a BackgroundService through a channel, or a pipeline stage that fans work out to N workers. Channels live in memory, so work that must survive a restart belongs in a durable message queue (Amazon SQS, Azure Service Bus, Google Cloud Pub/Sub, RabbitMQ).

Common mistakes

  • async void, and async lambdas passed as Action (List.ForEach, Parallel.ForEach, timers).
  • Not awaiting a task (warning CS4014). The work runs unobserved, and its exception is lost.
  • .Result / .Wait() in request code: deadlocks in UI and classic ASP.NET, starvation everywhere.
  • Dropping the CancellationToken halfway down the call chain, so a cancelled request keeps working.
  • return task; inside a using: the resource is disposed before the task finishes. Write return await task; there.
  • Task.Run to "make it async" in ASP.NET Core. It just moves the same work to another pool thread. Use Task.Run for CPU-bound work you want off the current thread, not to wrap I/O.
  • Unsynchronised shared state between concurrent tasks: List<T>.Add and count++ from several threads.

In a real codebase

Side note
// ASP.NET Core minimal API (not runnable here)
app.MapGet("/orders/{id:int}", async (int id, AppDbContext db, IShippingClient shipping, CancellationToken ct) =>
{
    var order = await db.Orders.FindAsync([id], ct);
    if (order is null) return Results.NotFound();

    var tracking = await shipping.GetTrackingAsync(order.TrackingCode, ct); // ct flows everywhere
    return Results.Ok(new { order.Id, order.Status, tracking.Eta });
});

The token comes from the framework, flows into EF Core and the HTTP client, and if the user closes the tab, both calls stop. Background work uses BackgroundService with a stoppingToken, often with PeriodicTimer for "every 30 seconds" loops. The .NET backend topic covers those.

JavaScript and F# compared

C# TaskJS PromiseF# async { }F# task { }
startsimmediately (hot)immediately (hot)when run (cold)immediately (hot)
threadsthread poolone threadthread poolthread pool
await on finished workcontinues synchronouslyalways a microtask hopcontinuescontinues synchronously
cancellationexplicit CancellationTokenAbortSignalimplicit, flows automaticallyexplicit token
wait for allTask.WhenAllPromise.allAsync.ParallelTask.WhenAll

F#'s task { } produces a real .NET Task, so it's what F# code uses to call (and be called by) C# libraries:

▶ Try
open System.Threading.Tasks

let getUser (id: int) = task {
    do! Task.Delay 50
    return $"user {id}"
}

let users = [ 1; 2; 3 ] |> List.map getUser |> Task.WhenAll
printfn "%A" users.Result

The exercises

  1. Sequential and concurrent lookups: await in a loop vs Task.WhenAll, with results in order.
  2. Heartbeat loop: a cancellable loop with Task.Delay(interval, token) and an exception filter.
  3. Timeout with linked tokens: TimeoutException for timeouts, OperationCanceledException for callers.
  4. Paged feed reader: an IAsyncEnumerable over continuation tokens, the way cloud list and query APIs page.
  5. Channel pipeline: a bounded Channel<T> with N workers, ordered results and fail-fast cancellation.
  6. Hedged requests: Task.WhenAny to race replicas, cancel the losers and collect every failure.

Practise this lesson

In the app: a short video, 6 exercises checked by real tests and a 10-question concept check. Free with a GitHub account. Running the exercises against their tests needs Pro.

Open in the app