skip to content

Async and Await

async and await over Task and ValueTask, contexts, cancellation, combinators, async streams and locks. Interviewers probe deadlocks, async void and lost exceptions.

on this pageshow

explore

questions

page 1 of 2

In C#, what is the difference between a CancellationTokenSource and a CancellationToken, and how does a cancel request reach an async method?

level: juniorimportance: must knowfreq 78%

answer

  1. sender and receiver
  2. one class, one readonly struct
  3. Cancel lives on only one of them
  4. last parameter, forwarded to every call

basics

~20 s

A CancellationTokenSource sends the request: Cancel, CancelAfter and Dispose live on it. A CancellationToken is the read-only struct that code receives to observe it. Each async method takes the token and forwards it to every call that accepts one.

solid answer

~40 s

The two types split the job. `CancellationTokenSource` is a class owned by whoever decides to stop the work, such as a Cancel button handler: it has `Cancel()`, `CancelAfter()` and `Dispose()`, and its `Token` property hands out a `CancellationToken`. The token is a `readonly struct` that can only observe: `IsCancellationRequested`, `ThrowIfCancellationRequested()`, `Register()` and `CanBeCanceled`. Code that receives a token cannot cancel anyone else's work. In an async call chain each method takes a `CancellationToken cancellationToken = default` as its last parameter and passes it to every awaited call that accepts one, such as `Task.Delay` or a stream's `ReadAsync`. Cancellation is cooperative: nothing stops code that never looks at the token.

code

csharp · 29 lines
csharp
using var cts = new CancellationTokenSource();

Task import = ImportAllAsync(["a.csv", "b.csv", "c.csv"], cts.Token);
await Task.Delay(150);   // the user clicks Cancel while b.csv is in progress
cts.Cancel();

try
{
    await import;
}
catch (OperationCanceledException)
{
    Console.WriteLine("Import cancelled");
}

static async Task ImportAllAsync(string[] files, CancellationToken cancellationToken)
{
    foreach (var file in files)
    {
        cancellationToken.ThrowIfCancellationRequested();
        await ImportFileAsync(file, cancellationToken);
        Console.WriteLine($"{file} imported");
    }
}

static async Task ImportFileAsync(string file, CancellationToken cancellationToken)
{
    await Task.Delay(100, cancellationToken);   // stands in for reading and saving the file
}

go deeper

for a junior

Recall which type has Cancel and which one methods take as a parameter, and show the token forwarded to every awaited call.

for a middle

Explain why cooperative cancellation means a method that never checks or forwards the token cannot be stopped, and where checkpoints belong in a loop.

for a senior

Show how you audit a call chain for a dropped token, using CA2016 and CA1068, and who owns and disposes each source.

for a principal

Weigh where a codebase draws the line between cancellable calls and calls that must finish, and how that rule is reviewed across teams.

## Two types, two roles .NET splits cancellation into a **sender** and a **receiver** so that the code doing the work can never cancel itself by accident, and the code that decides to stop does not need to know how the work is done. | | `CancellationTokenSource` | `CancellationToken` | |---|---|---| | Kind | class, implements `IDisposable` | `readonly struct` | | Who holds it | the owner of the decision (a Cancel button, a timeout, a parent operation) | every method that does cancellable work | | Can request cancellation | yes: `Cancel()`, `CancelAfter()`, the `CancellationTokenSource(TimeSpan)` constructor | no | | Can observe it | `IsCancellationRequested` | `IsCancellationRequested`, `ThrowIfCancellationRequested()`, `Register()`, `WaitHandle` | The source's `Token` property returns a token bound to that source. Many tokens can be handed out from one source, and they all report the same state. A `CancellationToken` is a small struct that wraps a reference to its source, so copying it is cheap and every copy sees the same request. ## How a request travels In the file-import job, the window owns a `CancellationTokenSource` and the Cancel button calls `Cancel()` on it. The import method never sees the source, only its token: 1. The window creates the source and calls `ImportAllAsync(files, cts.Token)`. 2. `ImportAllAsync` takes `CancellationToken cancellationToken` and passes it to `ImportFileAsync` for each file. 3. `ImportFileAsync` passes it again to the calls that actually wait: `Task.Delay`, `Stream.ReadAsync`, `HttpClient.GetAsync`, a database driver's async methods. 4. When the user clicks Cancel, `Cancel()` sets the source's state, and every token from it now reports `IsCancellationRequested == true`. 5. Whichever call is waiting at that moment notices, stops, and throws `OperationCanceledException` (or its subclass `TaskCanceledException`), which travels back up through each `await`. Nothing in this chain is automatic. **Cancellation is cooperative**: the token is a flag plus a notification mechanism, and only code that checks the flag or passes the token on will stop. A loop that never calls `ThrowIfCancellationRequested()`, or an awaited method called without the token, keeps running after Cancel. ## Conventions that keep the chain intact - **The parameter goes last** and is usually named `cancellationToken`, with `= default` on public APIs so callers can omit it. Code analysis rule **CA1068** ("CancellationToken parameters must come last") checks the position. - **Forward it to every call that accepts one.** Rule **CA2016** ("Forward the CancellationToken parameter to methods that take one") flags calls that could take the token but do not. In .NET 10 both rules are enabled by default only as suggestions, so they show in the IDE rather than failing a build. - **`default` and `CancellationToken.None` are the same value**: a token with no source, whose `CanBeCanceled` is `false`. Passing it means "this call cannot be cancelled", which is fine for a call that must finish but wrong as a lazy default deep inside a cancellable operation. - **Check at checkpoints in CPU-bound loops.** A loop that parses rows should call `cancellationToken.ThrowIfCancellationRequested()` every so often, before work that has side effects. - **Do not pass the source around.** Handing a `CancellationTokenSource` to a callee gives it the power to cancel the caller's other work and to dispose a source it does not own. ## The source's own lifetime A `CancellationTokenSource` implements `IDisposable`, and Microsoft's documentation asks you to call `Dispose()` when you have finished with it. After disposal, reading its `Token` property or calling `Cancel()` or `CancelAfter()` throws `ObjectDisposedException`, so the owner disposes it only once the work that uses its token has finished. A source created for one import run belongs in a `using` declaration in the method that owns that run. Tokens already handed out keep working as values after the source is disposed, but they can no longer be cancelled through it. ## Where this leaf stops Timeouts and combining the Cancel button with a deadline, how the cancelled task reports its outcome, `Register` callbacks and `Task.WaitAsync` each have their own question. The tokens a web host passes for an aborted request or for application shutdown are covered with ASP.NET Core, and passing a token into an `IAsyncEnumerable<T>` is covered with asynchronous sequences. Why cancellation is cooperative in every modern runtime, rather than a forced stop, is covered in the concurrency foundations.

  • In C#, why is CancellationToken a struct while CancellationTokenSource is a class?
    The source owns mutable shared state: the cancelled flag, registered callbacks and an optional timer, so it must be one object that everyone references. The token is only a handle to that source, a single reference wrapped in a `readonly struct`, so passing it by value through every call costs nothing extra and every copy still points at the same source. `default(CancellationToken)` simply has no source and can never be cancelled.
  • In a C# async method, what happens if one awaited call in the chain is made without forwarding the CancellationToken?
    That call cannot be interrupted. When the user cancels while it is running, it runs to completion, and the method only notices at its next check of the token, if there is one. If that call is the slow one, such as a large download, Cancel appears to do nothing for its whole duration. Code analysis rule CA2016 points out such calls when an overload with a token exists.

A building's fire alarm panel and its bells: only the panel can set the alarm off, every room has a bell that rings when it does, and the people in each room still have to walk out themselves; the bell carries nobody.

  • Passes the CancellationTokenSource itself down the call chain instead of its token
  • Believes calling Cancel() stops the running code even if it never checks the token
  • Calls async APIs without forwarding the token because the method's own loop checks it
  • Thinks CancellationToken.None is a token that is already cancelled
  • Disposes the source while work using its token is still running
open as a page

In C#, what does the lock statement compile to, and which object should a class lock on to guard its shared state?

level: juniorimportance: must knowfreq 66%

basics

~20 s

A C# lock (x) on an object becomes Monitor.Enter inside a try and Monitor.Exit in its finally, so an exception cannot leave the lock held. Lock on a private, dedicated object, never on this, a Type or a string.

open as a page

In C#, does marking a method async make it run on a background thread, and how much of it runs before the caller gets its Task?

level: juniorimportance: must knowfreq 60%

basics

~20 s

No. async lets a method use await and makes the compiler rewrite it; it starts no thread. The body runs on the caller's thread up to the first await of an unfinished operation, and a call that never suspends completes synchronously.

open as a page

In a C# async method, what does await do when the awaited Task has not finished yet, and what does the caller get back?

level: juniorimportance: must knowfreq 85%

basics

~20 s

When the awaited Task is still incomplete, await suspends the async method, hands an unfinished Task back to the caller, and runs the rest of the method later as a continuation. No thread is blocked during the wait.

open as a page

In C#, how do you give each imported file a 30-second limit while honouring the user's Cancel button, and tell the two apart?

level: middleimportance: must knowfreq 68%

basics

~10 s

Create a per-file CancellationTokenSource with a 30-second delay, combine it with the user's token through CancellationTokenSource.CreateLinkedTokenSource, and pass the linked token down. Afterwards, check which source has IsCancellationRequested set.

open as a page

In C#, why does awaiting three independent service calls one after another take longer than starting all three and awaiting Task.WhenAll?

level: middleimportance: must knowfreq 75%

basics

~20 s

Calling an async method starts its work; await only waits for it. Awaiting each call before making the next adds the three durations together, while starting all three first and awaiting Task.WhenAll costs roughly the slowest one.

open as a page

In C#, why does .Result on an async method freeze a desktop app's button handler but work fine inside an ASP.NET Core web API?

level: middleimportance: must knowfreq 80%

basics

~20 s

The library's await captures the UI SynchronizationContext and posts its continuation back to the UI thread, but that thread is blocked inside .Result waiting for it. ASP.NET Core has no SynchronizationContext, so the continuation runs on a thread-pool thread instead.

open as a page

Why does C# reject await inside a lock statement, and how do you protect shared state across an await with SemaphoreSlim?

level: middleimportance: must knowfreq 70%

basics

~20 s

A lock belongs to the thread that took it, and code after an await may resume on another thread, so C# rejects await inside lock with error CS1996. Use SemaphoreSlim(1, 1): await WaitAsync(), then Release() in a finally.

open as a page

In C#, when does returning IAsyncEnumerable<T> beat returning Task<List<T>>, and when is the list still the better return type?

level: middleimportance: must knowfreq 55%

basics

~20 s

Stream with IAsyncEnumerable<T> when results arrive over time and callers act on each: the first result comes early, memory stays bounded and the caller can stop. Return Task<List<T>> when callers need a complete, countable snapshot they can read twice.

open as a page

Why should a C# async method return Task rather than void, and what happens when an exception escapes an async void method?

level: middleimportance: must knowfreq 75%

basics

~20 s

An async void method gives callers no Task, so they cannot await it, learn when it finished, or catch its exceptions. An escaping exception is rethrown on the captured SynchronizationContext or, without one, on the thread pool, which terminates the process.

open as a page

In C#, when is Task.Run the right tool, and why is awaiting a truly asynchronous I/O method better than wrapping a blocking call in Task.Run?

level: middleimportance: must knowfreq 65%

basics

~20 s

Task.Run queues work to the thread pool, which suits CPU-bound work that must leave a UI thread. Wrapping blocking I/O in it still ties up a pool thread for the whole wait; a truly asynchronous API such as HttpClient.GetStringAsync holds none.

open as a page

When should a C# method return ValueTask<TResult> instead of Task<TResult>, and why does Task<TResult> remain the default choice?

level: middleimportance: must knowfreq 55%

basics

~20 s

Return ValueTask<TResult> from a hot method that usually completes synchronously, so the result travels inline without a Task allocation. Otherwise keep Task<TResult>: it has no consumption rules, and a plain async ValueTask method saves nothing when it really goes asynchronous.

open as a page

In C#, when two of the tasks passed to Task.WhenAll throw, why does a catch around await Task.WhenAll see only one exception, and how do you get them all?

level: seniorimportance: must knowfreq 60%

basics

~20 s

The task returned by Task.WhenAll faults with an AggregateException holding every failure, but await rethrows only the first of them, with its original type. Keep a reference to the combined task and read its Exception.InnerExceptions to see them all.

open as a page

In a C# async method, what exactly does await task.ConfigureAwait(false) change about where the following code runs, and when does it change nothing?

level: seniorimportance: must knowfreq 70%

basics

~20 s

ConfigureAwait(false) tells that one await not to capture the current SynchronizationContext or non-default TaskScheduler, so its continuation runs on an unspecified thread, usually the pool. It changes nothing when the task is already complete or when no context exists.

open as a page

In C#, how do you write a method that produces items asynchronously one at a time, and how does a caller loop over them?

level: juniorimportance: should knowfreq 55%

basics

~20 s

Mark the method async, return IAsyncEnumerable<T>, and use await and yield return in its body. The caller consumes it with await foreach, which awaits each element and runs the loop body as soon as that element is yielded.

open as a page

In C#, what is ValueTask<TResult>, and how should code that calls a ValueTask-returning method normally consume it?

level: juniorimportance: should knowfreq 45%

basics

~10 s

ValueTask<TResult> is a readonly struct that wraps either an already available result, a Task<TResult>, or an IValueTaskSource<TResult>. Callers should await it directly, exactly once, as soon as they get it.

open as a page

In a C# async method, what do ThrowIfCancellationRequested, OperationCanceledException and TaskCanceledException do, and how should a caller catch a cancellation?

level: middleimportance: should knowfreq 58%

basics

~10 s

ThrowIfCancellationRequested throws OperationCanceledException once the token is cancelled. An async Task method that ends with that exception completes as Canceled, not Faulted. TaskCanceledException derives from it, so callers catch OperationCanceledException.

open as a page

In C#, how do .Result, .Wait() and GetAwaiter().GetResult() differ when blocking on a Task, and does any of them avoid the UI deadlock?

level: middleimportance: should knowfreq 60%

basics

~20 s

.Result and .Wait() wrap a failure in AggregateException, while GetAwaiter().GetResult() throws the original exception as await would. All three block the calling thread, so none of them avoids the UI deadlock; only not blocking does.

open as a page

In C# 13 and later, what changes when a lock statement's target is a System.Threading.Lock rather than a plain object?

level: middleimportance: should knowfreq 28%

basics

~20 s

When the target's compile-time type is System.Threading.Lock (.NET 9), C# 13 lowers lock to using (x.EnterScope()) instead of Monitor calls. Converting that Lock to object brings back Monitor locking, which the compiler flags as warning CS9216.

open as a page

What does the C# compiler generate for an async method, and what jobs do MoveNext, the state field and the method builder each do?

level: middleimportance: should knowfreq 40%

basics

~20 s

The compiler emits a state-machine type implementing IAsyncStateMachine and a stub method. MoveNext runs the body up to each suspension, the state field records which await to resume at, and the method builder starts it and completes the returned Task.

open as a page

In .NET 10, what does System.Linq.AsyncEnumerable add for IAsyncEnumerable<T>, and what changes for code built on the System.Linq.Async package?

level: middleimportance: should knowfreq 30%

basics

~20 s

.NET 10 ships System.Linq.AsyncEnumerable: Where, Select, Take and the rest for IAsyncEnumerable<T>, plus terminal operators like ToListAsync that return ValueTask. It replaces the community System.Linq.Async package, which can cause ambiguity errors until removed or upgraded.

open as a page

In a C# async iterator, when does the method body start running, and what runs when the consumer breaks out of await foreach early?

level: middleimportance: should knowfreq 40%

basics

~20 s

Calling an async iterator runs none of its body; it starts at the first MoveNextAsync. When await foreach exits early by break or exception, it awaits DisposeAsync, which runs only the iterator's pending finally blocks and using disposals.

open as a page

In C#, how should a Task-returning method hand back a result it already has, and what do Task.FromResult and Task.CompletedTask provide?

level: middleimportance: should knowfreq 45%

basics

~20 s

Return Task.FromResult(value) for a Task<T>, or Task.CompletedTask for a plain Task, from a method not marked async. Both are already-completed tasks, so the caller's await continues without suspending; Task.FromException returns a faulted one for errors.

open as a page

A C# import wraps a parser that takes no CancellationToken in parseTask.WaitAsync(TimeSpan.FromSeconds(30)); why do slow files keep writing rows after the timeout fires?

level: seniorimportance: should knowfreq 42%

basics

~10 s

Task.WaitAsync times out only the wait: it returns a new task that faults with TimeoutException, while the original parse task keeps running. Cancellation is cooperative, so stopping the parser needs a token it checks.

open as a page

In a C# method, `_ = WriteAuditAsync();` discards a Task that later throws; what happens to that exception on .NET 10, and how should the call be fixed?

level: seniorimportance: should knowfreq 50%

basics

~20 s

The exception is stored in the discarded task and nothing reports it. On .NET 10 the process keeps running; TaskScheduler.UnobservedTaskException fires only if the faulted task is later finalized. Await the call, or hand the task to an owner that observes it.

open as a page

In C#, you race a slow call against Task.Delay with Task.WhenAny to impose a timeout; what happens to the call that lost, and to any exception it throws later?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Task.WhenAny only reports which task finished first; it never cancels the others. The losing call keeps running, and if it faults later with nobody awaiting it, its exception goes unobserved. Pass it a CancellationToken and cancel it.

open as a page

In C#, does a value in an AsyncLocal<T> survive an await with ConfigureAwait(false), and why does SynchronizationContext.Current behave differently?

level: seniorimportance: should knowfreq 35%

basics

~10 s

Yes. AsyncLocal<T> lives in the ExecutionContext, which every await carries to its continuation regardless of ConfigureAwait. SynchronizationContext.Current is captured and posted to, not flowed, so a thread-pool continuation or a Task.Run delegate sees null.

open as a page

A C# rate counter runs _hits++ on many threads and loses counts; why doesn't marking the field volatile fix it, and when is Interlocked enough instead of lock?

level: seniorimportance: should knowfreq 55%

basics

~20 s

_hits++ is a load, an add and a store, so two threads can store the same value. volatile only limits how single reads and writes are reordered; Interlocked.Increment makes the update atomic. Fields that must change together need lock.

open as a page

What does C#'s Lazy<T> guarantee by default when many threads read Value, and how do LazyThreadSafetyMode and a throwing factory change that?

level: seniorimportance: should knowfreq 38%

basics

~20 s

new Lazy<T>(factory) defaults to LazyThreadSafetyMode.ExecutionAndPublication: a lock lets one thread run the factory and all threads get its value. If that factory throws, Lazy caches the exception; PublicationOnly instead retries, but may run the factory on several threads.

open as a page

A C# async cache lookup usually finds its value already loaded: what does each call allocate on the hit path versus the miss path, and why?

level: seniorimportance: should knowfreq 30%

basics

~20 s

On a hit the awaited Task is already complete, so nothing suspends: the struct state machine stays on the stack and only the returned Task<T> may allocate. A miss boxes the machine once, and that box is the returned Task.

open as a page

showing 1–30 of 42