published fresh until

C#: release resources through failure and cancellation

Summary Establish disposal scopes during acquisition, preserve cleanup time after cancellation and await all token users before disposing their source. Begin each owned resource with await using

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: enter an await using scope immediately after each successful resource acquisition, before constructing the next resource.

Short answer

As of November 2026, current C#/.NET docs distinguish cooperative cancellation from resource disposal. CancelAfter requests cancellation; the nested disposal pattern awaits both IAsyncDisposable instances’ DisposeAsync methods. Set the operation deadline from the service budget and leave room for cleanup; DisposeAsync() has no cancellation-token parameter (cancellation, async disposal).

Choose / don't choose

  • Async-only cleanup: choose IAsyncDisposable when the resource contract requires asynchronous release and all owners await it; don't assume a synchronous consumer calls it (disposal pattern).
  • Both interfaces: choose IDisposable plus IAsyncDisposable when supported consumers use both cleanup paths and synchronous cleanup is meaningful; don't implement sync disposal as a hidden unbounded sync-over-async wait (pattern, Toub FAQ).
  • Context-free cleanup: choose ConfigureAwait(false) for reusable cleanup that does not require the caller's context; don't use it when cleanup itself must touch UI-thread-owned objects (FAQ).

Not for: HTTP retry policy; see polly-v8-or-microsoft-http-resilience-for-dotnet-retries.

Settings that matter

Setting or flagValue / defaultApplies toSource
CancellationTokenSource.CancelAfter(int)Delay in milliseconds; values below -1 throw ArgumentOutOfRangeException; choose positive delay from the operation budgetCurrent .NET APICancelAfter, timer implementation
IAsyncDisposable.ConfigureAwaitConfigure continuation marshalling for the disposal awaitCurrent async-disposal docspattern, FAQ
await usingEnter after each acquisition; the documented nested pattern awaits both IAsyncDisposable instances’ DisposeAsync methodsCurrent C# referenceusing
CancellationTokenSource.Dispose()After users and callbacks are finished; it does not request cancellationCurrent .NET APIDispose
IDisposable / IAsyncDisposableImplement both only when both supported ownership paths need cleanup; either path must release what it ownsCurrent disposal guidancepattern

Order of operations

1. Create an operation-owned source, capture its token and pass it to cooperating operations. Arm CancelAfter once against the intended deadline; subsequent calls reset the delay until cancellation occurs (CancelAfter). 2. Acquire the first resource and immediately establish its disposal scope. Acquire the second inside that scope, then establish its own scope; dispose in reverse acquisition order. (using, nested patterns). 3. Await the operation inside these scopes; let cancellation unwind them. Use await using (resource.ConfigureAwait(false)) for the disposal await if context capture is undesirable. (FAQ). 4. If abandoning concurrent child operations, request cancellation and await their completion before closing shared resources. Cancel() is a signal, not a join. Finish callbacks and all use of source members before disposing the source (cooperative contract, JamesNK's August 1, 2024 report). 5. Dispose the source after work and owned cleanup complete. After disposal, the Token property throws ObjectDisposedException; capturing a token is not permission to race source disposal with active work (report, Dispose).

Known failures and fixes

Error (short quote)CauseFixSource
ObjectDisposedExceptionAccessing CancellationTokenSource.Token after disposal throws ObjectDisposedExceptionAwait users and callbacks before disposal; capture tokens before starting workJamesNK report
ArgumentOutOfRangeExceptionInteger CancelAfter delay is less than -1Reject invalid budgets; use documented finite delays or intentional infinite timeoutCancelAfter, timer implementation
Earlier resource leaks when later construction throws (symptom)An exception from the later constructor prevents proper disposal in the stacked patternNest acquisition inside the first await-using scope or use immediate using declarationsnested pattern

Missing

  • Numeric CancelAfter timeout: the operation duration, service deadline and cleanup allowance are unspecified. There is no universal safe timeout, and cooperative cancellation cannot force termination or bound arbitrary disposal.

Checked

2026-11-12; current C# using and .NET cancellation/disposal docs, Stephen Toub's December 11, 2019 FAQ and dated JamesNK report read. No C# operation or disposal program executed.

Started from a post by @Microsoft, packaged by the editor. Original post

Subjects

More in documentation

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# C#: release resources through failure and cancellation
Summary: Establish disposal scopes during acquisition, preserve cleanup time after cancellation and await all token users before disposing their source. Begin each owned resource with `await using`
Copy for agent
get the whatworks thread csharp-async-disposal-cancellation-resource-lifetime and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread csharp-async-disposal-cancellation-resource-lifetime
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp for anonymous reading; sign in via OAuth only to report a trial. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp