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.
In short
Task<T>isPromise<T>, and tasks are hot- Code after
awaitmay run on another thread awaitin a loop is sequential;Task.WhenAlloverlaps- Take a
CancellationTokenand pass it on - Never
.Result,.Wait()orasync 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
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
| TypeScript | C# |
|---|---|
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 promise | Task.Delay(ms) |
Promise.all | Task.WhenAll |
Promise.race | Task.WhenAny (returns the first task to finish) |
AbortController / AbortSignal | CancellationTokenSource / CancellationToken |
async function* and for await | IAsyncEnumerable<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
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;
}
- An async method runs synchronously until it awaits a task that isn't finished yet. Then it returns an
incomplete
Taskto its caller. - The compiler rewrites the method into a state machine: a struct whose
MoveNext()method holds your code cut into pieces at eachawait. Local variables become fields so they survive between pieces. - When the awaited task completes, it calls
MoveNext()again, which jumps to the right piece and carries on. - 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.
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.
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:
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.
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;
}
awaitthrows the first exception..Wait()and.Resultwrap everything in anAggregateException, one more reason to avoid them.- When several tasks in a
Task.WhenAllfail,awaitthrows just one of them (which one depends on the .NET version and the overload, so don't rely on it). TheTaskreturned byWhenAllhas all of them intask.Exception.InnerExceptions. async voidmethods have no task to store the exception in. It's rethrown on the thread pool and crashes the process. Only useasync voidfor UI event handlers. Watch out for async lambdas passed where anActionis expected:items.ForEach(async x => await SaveAsync(x))isasync voidin disguise. It also doesn't wait for anything.
Running work concurrently
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;
awaitin 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.Selectis lazy:WhenAllenumerates 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.awaitit 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.ForEachAsyncandMaxDegreeOfParallelism, aSemaphoreSlim, or aChannel<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:
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.
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.DelayandHttpClientthrow its subclassTaskCanceledException, so catch the base type. - Who cancelled?
HttpClientthrowsTaskCanceledExceptionwhen its ownTimeoutexpires, 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, useCancellationTokenSource.CreateLinkedTokenSource(callerToken)and callCancelAfteron 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 = ...), becauseCancelAfteruses a timer.
| TypeScript | C# |
|---|---|
new AbortController() | new CancellationTokenSource() |
controller.signal | cts.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 everyawait, 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 needConfigureAwait(false). You'll still see it in older code and libraries. It's harmless. .Resultand.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 synchronousMain, use.GetAwaiter().GetResult(), which at least throws the real exception instead of anAggregateException.
IAsyncEnumerable: async streams
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 foreachdisposes the enumerator, which runs the producer'sfinallyblocks. [EnumeratorCancellation]connects a token passed throughsource.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>, soawait foreachwalks every page for you) and with EF Core'sAsAsyncEnumerable(). ASP.NET Core can also stream anIAsyncEnumerable<T>result as a JSON array. - It's the C# twin of TypeScript's
async function*andfor 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.
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
BackgroundServicethrough 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 asAction(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
CancellationTokenhalfway down the call chain, so a cancelled request keeps working. return task;inside ausing: the resource is disposed before the task finishes. Writereturn await task;there.Task.Runto "make it async" in ASP.NET Core. It just moves the same work to another pool thread. UseTask.Runfor CPU-bound work you want off the current thread, not to wrap I/O.- Unsynchronised shared state between concurrent tasks:
List<T>.Addandcount++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# Task | JS Promise | F# async { } | F# task { } | |
|---|---|---|---|---|
| starts | immediately (hot) | immediately (hot) | when run (cold) | immediately (hot) |
| threads | thread pool | one thread | thread pool | thread pool |
await on finished work | continues synchronously | always a microtask hop | continues | continues synchronously |
| cancellation | explicit CancellationToken | AbortSignal | implicit, flows automatically | explicit token |
| wait for all | Task.WhenAll | Promise.all | Async.Parallel | Task.WhenAll |
F#'s task { } produces a real .NET Task, so it's what F# code uses to call (and be called by) C# libraries:
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
- Sequential and concurrent lookups:
awaitin a loop vsTask.WhenAll, with results in order. - Heartbeat loop: a cancellable loop with
Task.Delay(interval, token)and an exception filter. - Timeout with linked tokens:
TimeoutExceptionfor timeouts,OperationCanceledExceptionfor callers. - Paged feed reader: an
IAsyncEnumerableover continuation tokens, the way cloud list and query APIs page. - Channel pipeline: a bounded
Channel<T>with N workers, ordered results and fail-fast cancellation. - Hedged requests:
Task.WhenAnyto 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