Async resource ownership
Async resource ownership
Asynchronous resources may need to finish cleanup through an awaitable operation. IAsyncDisposable exposes DisposeAsync, and await using arranges to await cleanup when control leaves the scope. Own resources explicitly, including tasks that use them.
Examples target the proposed C# 14 / .NET 10 console baseline (one independent Program.cs per example, nullable enabled). Expected outputs are reasoned, not executed. Source-generation examples require the standard SDK and its built-in generators; no extra packages or external services are used.
Dispose after an operation fails
Use await using inside a try block so cleanup completes before the surrounding catch handles the operation error. This mock prints a lifecycle trace.
using System;using System.Threading;using System.Threading.Tasks;using var stop = new CancellationTokenSource();try{ await using var lease = new Lease(); Console.WriteLine("open"); stop.Cancel(); stop.Token.ThrowIfCancellationRequested();}catch (OperationCanceledException) { Console.WriteLine("canceled"); }sealed class Lease : IAsyncDisposable{ public ValueTask DisposeAsync() { Console.WriteLine("disposed"); return ValueTask.CompletedTask; }}The implicit finally awaits disposal before the exception reaches catch. The mock cleanup completes immediately; real cleanup may suspend.
Expected output (reasoned, not executed):
opendisposedcanceledConsume ValueTask once
ValueTask<T> can represent an inline result or an asynchronous operation. Prefer Task<T> by default; consider ValueTask when measurement and usage patterns justify it. Treat each returned ValueTask as single-use; if repeated awaits are necessary, convert once to a Task and use only that task.
using System;using System.Threading.Tasks;ValueTask<int> pending = CachedCount();int count = await pending;Console.WriteLine(count);static ValueTask<int> CachedCount() => new ValueTask<int>(6);The value is already available. No allocation or performance guarantee is inferred from this fixture.
Expected output (reasoned, not executed):
6Distinguish continuation context from ambient data
SynchronizationContext can route callbacks to a context such as a UI thread. A nondefault TaskScheduler may also affect task continuations. ConfigureAwait(false) avoids requesting the captured scheduling context for this await, not a forced thread switch. AsyncLocal values normally flow via ExecutionContext.
using System;using System.Threading;using System.Threading.Tasks;var label = new AsyncLocal<string?>();label.Value = "batch-7";await Task.Run(async () =>{ await Task.CompletedTask.ConfigureAwait(false); Console.WriteLine(label.Value);});The normal ExecutionContext flow into Task.Run carries the label. The completed await need not switch threads.
Expected output (reasoned, not executed):
batch-7Common mistakes and edge cases
Do not let fire-and-forget work outlive a resource it uses. Await its completion or hand it to an explicitly managed owner. Disposal may itself fail; decide how to preserve primary and cleanup errors in production. ConfigureAwait(false) neither eliminates all deadlocks nor replaces thread-safe design. Never place secrets in ambient labels.
Practice and recap
Add a second Lease in a nested scope, printing open A, open B, then leaving both scopes normally. Predict disposal order if the leases print their names.
Hint: Dispose nested scopes from inside outward.
Learning objective: Dispose async resources even on cancellation. See accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Async resource ownership — knowledge check
Apply the lesson concepts to the following scenarios.
What does await using arrange?
What prints before canceled in the fixture?
How should consumers handle a general ValueTask result?
Does ConfigureAwait(false) force a new thread?
What normally carries AsyncLocal across awaits?