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 pageshowhide
explore
- Task-Based Methods6 questions
- Compiler State Machine4 questions
- ValueTask Rules4 questions
- Contexts and Deadlocks6 questions
- Cancellation Tokens5 questions
- Combinators and Failures6 questions
- Asynchronous Sequences6 questions
- Locks and Atomics5 questions
questions
page 2 of 2In C#, why can a token passed with WithCancellation fail to reach an async iterator, and what does [EnumeratorCancellation] change?
basics
~20 sWithCancellation passes its token to GetAsyncEnumerator, and an async iterator ignores that token unless one CancellationToken parameter carries [EnumeratorCancellation]. With the attribute, the body sees that token, combined with any token passed as an argument.
In C#, what changes when a method returns another method's Task directly instead of awaiting it, for exceptions and for a using block around the call?
basics
~20 sReturning the inner task without async and await ends the method at its return: a using block disposes the resource mid-operation, a catch misses the task's later failures, and the method's own exceptions throw at the call rather than faulting the task.
A C# ValueTask<int> from a pooled reader works on its first await but throws InvalidOperationException when awaited again; what rule was broken, and how do you fix it?
basics
~20 sA ValueTask must be consumed once: one await, never concurrent awaits, no Result before completion. A pooled IValueTaskSource is reused once its result is read, so the stale token is rejected; await once, or use AsTask() or Preserve().
Your team's C# batch job calls an API for 10,000 ids with async code; what policy would you set for bounding concurrency, failures and fire-and-forget tasks?
basics
~20 sNever fan 10,000 calls out unbounded: gate them with SemaphoreSlim or an equivalent limit set from the downstream's capacity, decide per job whether to fail fast or collect each outcome, put one deadline on the group, and ban untracked fire-and-forget tasks.
As the lead for a C# library shared by desktop apps and ASP.NET Core services, what ConfigureAwait rule would you set for the team, and how would you enforce it?
basics
~20 sA common rule: library code uses ConfigureAwait(false) on every await, enforced by analyzer CA2007 on library projects only; app code keeps the default; the library ships no sync-over-async wrappers. The costs are noise and missed awaits.
Your team is moving a synchronous C# weather library, and the console tool and desktop app that call it, to async; where do you start, how far do you go, and where do you stop?
basics
~20 sStart at the I/O calls, switch them to truly asynchronous APIs, and let Task-returning signatures spread up to the entry points: async Main in the console tool, async event handlers in the desktop app, with no .Result bridges or Task.Run wrappers between.
In C# on .NET 9 or later, how does Task.WhenEach let you handle tasks in the order they finish, and what replaced it before?
basics
~20 sTask.WhenEach, added in .NET 9, returns an IAsyncEnumerable of the input tasks that yields each one as it completes, so await foreach handles them in completion order. Earlier code looped over Task.WhenAny and removed each finished task.
In C#, where does a CancellationToken.Register callback run, and why must an import service dispose the registrations and linked CancellationTokenSources it creates?
basics
~20 sA Register callback runs synchronously on the thread that cancels: inside Cancel(), or on a thread-pool thread when a CancelAfter timer fires. A long-lived source keeps every registration, including a linked source's, until disposed or cancelled.
In C# on .NET 8 and later, what do the ConfigureAwaitOptions flags for Task.ConfigureAwait do, and why does SuppressThrowing fail on a Task<TResult>?
basics
~20 sConfigureAwaitOptions (.NET 8) replaces the bool: ContinueOnCapturedContext resumes on the captured context, SuppressThrowing completes the await without throwing, ForceYielding suspends even on a finished task. SuppressThrowing on Task<TResult> throws ArgumentOutOfRangeException, since no valid result exists.
In C#, what must a type provide for await to accept it, and in what order does compiled code call a custom awaiter's members?
basics
~20 sawait is pattern-based: the type needs an accessible GetAwaiter() method, instance or extension, whose awaiter has a bool IsCompleted, a GetResult() method and implements INotifyCompletion. Compiled code calls IsCompleted, then OnCompleted only if unfinished, then GetResult.
In C# library code, what does ConfigureAwait(false) on an await foreach loop configure, and why can the loop body still run on the captured context?
basics
~20 ssource.ConfigureAwait(false) configures only the awaits that await foreach generates on MoveNextAsync and DisposeAsync. Awaits inside the async iterator are configured by the iterator's own code; if they capture the context, the loop body can still run there.
When should a C# interface or virtual method that other teams implement return ValueTask<int> rather than Task<int>, as Stream.ReadAsync(Memory<byte>) does?
basics
~20 sUse ValueTask<int> in an interface or virtual signature when many implementations will complete synchronously or want to pool operations, as buffered streams do. The choice binds every implementer and caller, and changing it later is a breaking change.
showing 31–42 of 42