Deterministic Cleanup Calls and Resource Release with Async Scope Guards
Asynchronous programs frequently deal with resources that must be returned after use, such as connections, work slots, and temporary upload sessions. The problem is that when you write acquisition and release as separate ordinary function calls, it is easy to miss the release call on one of the return, exception, or cancellation paths. An Async Scope Guard binds a resource's lifetime to its lexical scope.
· Practice memo · 51 min read · Medium
Async programs constantly hold resources that have to go back after use: connections, work slots, temporary upload sessions. Write acquisition and release as two plain calls and some return, exception, or cancellation path will eventually miss the release.
An Async Scope Guard binds a resource's lifetime to a lexical scope. C#'s await using, TypeScript's await using, and Python's async with all await the asynchronous cleanup when the block exits. C++ is closer to the original synchronous RAII model, but because destructors cannot be coroutines, the coroutine function itself must own the entire acquire -> use -> release sequence for asynchronous cleanup. (In fact, memorizing the acquire->use->release formula is essentially all you need to understand this entire document.) C#'s await using uses IAsyncDisposable, TypeScript calls [Symbol.asyncDispose](), and Python calls __aenter__() and __aexit__().1234
A note on the word deterministic here: it means the cleanup entry point gets called and its completion awaited within normal control flow. It does not stop a forced process kill or a power loss, and it does not guarantee that a remote release over the network succeeds or lands exactly once.
This is not about getting rid of try/finally. It is about pushing the repeated try/finally into a protocol on the resource type: the caller no longer re-implements "when do I release this" on every path, and the resource implementor owns "how do I release it" in one place.
Release has to be async because the return trip is itself I/O: handing back a remote work slot, rolling back a transaction, flushing a buffered stream, the next operation is only safe once those finish. .NET's IAsyncDisposable.DisposeAsync() says the same thing by returning a ValueTask that represents the async cleanup.
Formula to memorize:
Here, "once" means the guard does not call the broker's cleanup entry point more than once. When a network response is lost, the client cannot know whether the remote release was applied. The broker must provide idempotent release (retryable with the same leaseId) and lease expiration. Attaching the phrase "exactly once" directly to remote effects overstates the guarantee.5
1. The Problem
Take a rendering server that borrows a capped number of GPU work slots from a central coordinator.
RenderSlotBroker:
- acquireAsync()
- releaseAsync(token)
RenderSlotToken:
- slotId
- leaseIdThe flow goes like this.
1. Acquire Rendering Slot
2. Execute Rendering
3. Return SlotMid-render, any of these can blow up.
- Normal completion
- Input file parsing failure
- GPU operation failure
- Caller cancellation
- Early return from methodWith manual release, every one of those paths has to run this.
await broker.releaseAsync(token)Miss a single path and the slot never comes back: later work queues up behind it, or worse, the coordinator ends up holding a wrong active-slot count.
The API I want looks like this.
await using / async with
Inside the block, `slotId` is used
When the block exits, `releaseAsync` is executed automaticallyIt comes down to one thing: binding an async lease's acquisition and release to a lexical scope.
2. Core Expressions
Common contract:
RenderSlotBroker
- Validates the response format and token before `acquire` returns normally
- Copies the external response into an immutable/plain token value internal to the language
- Transfers token ownership to the caller upon normal return
- For acquisitions with ambiguous results (such as timeouts), recovers the resource using a request id and lease TTL
RenderSlotLease
- `acquire`: asynchronous
- `getSlotId`: usable only while active
- `dispose`/`exit`: asynchronous
- Sequential duplicate release after completion: no-op
- Concurrent `dispose` callers: outside the scope of this example
- Reuse after release has begun: prohibitedThe catch is that the coordinator may have already claimed a slot and then answered with a bad token. If the lease factory throws while validating that token, the scope guard does not exist yet. The classic mistake is running only ValidateToken() while the slot is already live, which leaks it, and if the leaseId came back empty the client has no way to know what to release.
So the broker in this example carries the contract that any token it returns normally is already validated and returnable. Parsing the HTTP/gRPC response, validating the token, and recovering from an ambiguous acquire outcome are all the broker adapter's job. The lease factory builds the wrapper right after a successful return, and nothing that can fail may sit between the acquire and the wrapper construction.
C++: Where RAII Ends
In C++, resources that clean up synchronously, such as files, mutexes and memory, sit most naturally under RAII: the local object leaves scope, the destructor runs on its own, and you never enumerate the return paths and the exception paths separately.
The remote lease this document covers is a different matter. If returning a slot requires network I/O, co_await is needed to wait for completion, yet a C++ destructor cannot be a coroutine.46
This is the code I got wrong when I first wrote it, and it is a spot plenty of C++ beginners trip over too.
class RenderSlotLease {
public:
~RenderSlotLease() {
co_await broker_.release(token_); // Error: a destructor cannot be a coroutine.
}
};Blocking the event loop in the destructor and calling future.get() is not a good workaround either. If the same thread's event loop is what has to drive the release to completion, you deadlock right there, and even without a deadlock you should know that one destructor call can introduce an unexpectedly long stall. Hand it to a fire-and-forget like co_spawn(..., detached) and the scope ends before cleanup is done, with the errors detached from the call path.
If a destructor emits an exception during stack unwinding, std::terminate may be called, so hiding a potentially failing async release inside a destructor is fundamentally the wrong approach.4
In C++, therefore, the clearer approach is to close synchronous resources with RAII and let a coroutine-level bracket function own the entire lifecycle of async resources. Because the standard C++ coroutine mechanism defines only the language machinery and provides no general-purpose Task<T> runtime, the examples below use Boost.Asio's boost::asio::awaitable<T>. If you are using an actual task type from Folly, Seastar, Qt, or similar, you only need to change the return type and cancellation API to match that runtime.67
#include <boost/asio.hpp>
#include <exception>
#include <optional>
#include <stdexcept>
#include <string>
#include <utility>
namespace asio = boost::asio;
struct RenderSlotToken {
std::string slot_id;
std::string lease_id;
};
struct RenderJob {
std::string job_id;
std::string input_key;
};
struct RenderReceipt {
std::string job_id;
std::string output_key;
};
class RenderSlotBroker {
public:
virtual asio::awaitable<RenderSlotToken> acquire() = 0;
// Apply a short timeout decoupled from the caller's cancellation, along with idempotent release, internally.
virtual asio::awaitable<void> release_for_cleanup(
RenderSlotToken token) = 0;
virtual ~RenderSlotBroker() = default;
};
class Renderer {
public:
virtual asio::awaitable<RenderReceipt> render(
RenderJob job,
std::string slot_id) = 0;
virtual ~Renderer() = default;
};
class RenderAndCleanupFailed final : public std::runtime_error {
public:
RenderAndCleanupFailed(
std::exception_ptr body_error,
std::exception_ptr cleanup_error)
: std::runtime_error("render and slot cleanup both failed"),
body_error_(std::move(body_error)),
cleanup_error_(std::move(cleanup_error)) {}
const std::exception_ptr& body_error() const noexcept {
return body_error_;
}
const std::exception_ptr& cleanup_error() const noexcept {
return cleanup_error_;
}
private:
std::exception_ptr body_error_;
std::exception_ptr cleanup_error_;
};
asio::awaitable<RenderReceipt> execute_render_job(
RenderJob job,
RenderSlotBroker& broker,
Renderer& renderer)
{
// A token returned normally has already been validated by the broker.
RenderSlotToken token = co_await broker.acquire();
std::optional<RenderReceipt> receipt;
std::exception_ptr body_error;
try {
receipt.emplace(
co_await renderer.render(
std::move(job),
token.slot_id));
} catch (...) {
// Store the original error so it can be re-thrown after cleanup.
body_error = std::current_exception();
}
std::exception_ptr cleanup_error;
bool was_cancelled = false;
try {
// Asio may throw an exception at the next `co_await` after a coroutine has been cancelled.
// Disable automatic throwing only during cleanup. This setting alone does not remove the
// cancellation that has been propagated to sub-operations, so the broker contract below must
// provide a separate timeout/cancellation boundary.
// This helper assumes the general policy that `throw_if_cancelled(true)` was in effect upon entry.
co_await asio::this_coro::throw_if_cancelled(false);
co_await broker.release_for_cleanup(std::move(token));
} catch (...) {
cleanup_error = std::current_exception();
}
// `throw_if_cancelled(true)` does not re-throw a cancellation that has already occurred.
// Therefore, observe the cancellation state after cleanup, and if necessary,
// produce the cancellation result explicitly below.
try {
auto cancellation_state =
co_await asio::this_coro::cancellation_state;
was_cancelled = cancellation_state.cancelled()
!= asio::cancellation_type::none;
} catch (...) {
if (!cleanup_error) {
cleanup_error = std::current_exception();
}
// If a release failure has already occurred, preserve that error.
}
if (body_error && cleanup_error) {
throw RenderAndCleanupFailed(
std::move(body_error),
std::move(cleanup_error));
}
if (cleanup_error) {
std::rethrow_exception(cleanup_error);
}
if (body_error) {
std::rethrow_exception(body_error);
}
if (was_cancelled) {
throw asio::system_error(asio::error::operation_aborted);
}
co_return std::move(receipt).value();
}The contract of release_for_cleanup() is critical here. It does not propagate the caller's cancellation as-is, but that does not mean it waits indefinitely. The broker must apply a separate short timeout and ensure that resending the same release request using the lease_id is safe. Because a co_await that resumes inside a cancelled Boost.Asio coroutine can throw by default, it is important to apply throw_if_cancelled(false) for the duration of the cleanup.7
This setting only disables the automatic-throw behavior on the next co_await; it does not prevent the already-delivered cancellation slot from cancelling lower-level async operations. The broker must therefore own a separate cleanup execution flow, a timeout, and idempotent release. Simply calling throw_if_cancelled(true) after cleanup does not replay a cancellation that has already been delivered, so the example observes the cancellation_state and then constructs the cancellation result explicitly. Because co_await cannot appear inside a catch handler in C++8, the release and the state observation are each collected inside try blocks.
reset_cancellation_state() is the stronger tool, but that state is shared by the coroutines co_spawn put in the same execution chain. Reset it in a lower-level helper and return as-is, and you may have changed the caller's cancellation policy too. That is why the outer bracket function only switches off the automatic throw for a moment instead of resetting the state.
Inside release_for_cleanup(), by contrast, the scope is already closed, so the stronger tool fits. If real operations like async_write or async_connect must not be interrupted by caller cancellation, either write a small helper inside the broker that applies reset_cancellation_state(disable_cancellation()), or isolate the release in a new co_spawn chain with its own timeout. throw_if_cancelled(false) only turns off the automatic throw on the next co_await; it does not keep an already-delivered cancellation slot from cancelling lower-level async operations. So the point of this example is not "ignore caller cancellation and wait forever" but "finish the release under a broker-owned timeout that is independent of caller cancellation." Examples like this are easiest to memorize whole, and that is how I apply them.
The lifetime of coroutine inputs also deserves separate attention: value parameters are moved into the coroutine frame, but reference parameters remain as references. So if you pass a temporary object like execute_render_job(RenderJob{...}, ...) and the coroutine then suspends, the const RenderJob& becomes a dangling reference.6
RenderJob and slot_id come in by value so the frame owns them. broker and renderer stay as references, on the premise of a service-lifetime contract: the caller keeps them alive until the work is done.
The C++ implementation carries the body error and the cleanup error in two separate std::exception_ptr values, and reporting that pair safely through one ordinary RAII destructor is genuinely hard. That is just how it is.
For synchronous cleanup, a destructor, Library Fundamentals TS v3's std::experimental::scope_exit, or Boost.Scope's scope guard may be the right fit. Note that std::scope_exit is not the name that made it into the C++23 standard library.9 Fallible async cleanup must be finished at an awaitable orchestration boundary. This example assumes a policy of using exceptions as the error channel. In a project that models all predictable failures as Result values, the same four steps must be composed as values instead, and the concrete form of that is covered in a later section.
A personal note: I'm writing C++ for the first time in a while, going through the code I saved and used before plus GitHub examples to trace where it all came from, and C++ docs feel badly fragmented, with far too many things you simply have to memorize.
C#
The example uses record struct, so it targets C# 10 or later. The runnable code uses ArgumentNullException.ThrowIfNull(), which requires .NET 6 or later. await using and IAsyncDisposable themselves have been available since C# 8 / .NET Core 3.0.1
using System;
using System.Threading;
using System.Threading.Tasks;
public readonly record struct RenderSlotToken(
string SlotId,
string LeaseId);
public interface IRenderSlotBroker
{
ValueTask<RenderSlotToken> AcquireAsync(
CancellationToken cancellationToken);
ValueTask ReleaseAsync(
RenderSlotToken token);
}
public sealed class RenderSlotLease : IAsyncDisposable
{
private readonly RenderSlotToken token;
private IRenderSlotBroker? broker;
private int disposeStarted;
private RenderSlotLease(
IRenderSlotBroker broker,
RenderSlotToken token)
{
this.broker = broker;
this.token = token;
}
public static async Task<RenderSlotLease> AcquireAsync(
IRenderSlotBroker broker,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(broker);
RenderSlotToken token =
await broker.AcquireAsync(cancellationToken)
.ConfigureAwait(false);
// A token returned normally by the Broker has already been validated,
// and this constitutes a contract that the caller may take on the responsibility of returning it.
return new RenderSlotLease(broker, token);
}
public string GetSlotId()
{
this.EnsureActive();
return this.token.SlotId;
}
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref this.disposeStarted, 1) != 0)
{
return;
}
IRenderSlotBroker? owner = this.broker;
this.broker = null;
if (owner is null)
{
return;
}
await owner.ReleaseAsync(this.token)
.ConfigureAwait(false);
}
private void EnsureActive()
{
if (Volatile.Read(ref this.disposeStarted) != 0)
{
throw new ObjectDisposedException(
nameof(RenderSlotLease));
}
}
}Usage syntax:
await using RenderSlotLease lease =
await RenderSlotLease.AcquireAsync(
broker,
cancellationToken);
string slotId = lease.GetSlotId();Leaving the scope of an await using block or declaration calls DisposeAsync(). C#'s using family is lowered so that the cleanup call is not skipped even when the block throws or a return runs.
The type rests on the premise that a single scope owns the lease alone. All Interlocked.Exchange() buys you is that concurrent dispose calls do not start a duplicate remote release; it is not a borrow protocol that makes GetSlotId() and DisposeAsync() safe to call from different threads at the same time. If you handed the lease to another task, await every one of those tasks before the scope ends.
The public factory returns Task<RenderSlotLease>. ValueTask<T> is also viable if it is awaited exactly once, but it generally carries a consumption contract that says you must not await it more than once or mix it with AsTask(). For a public acquisition API without a measured allocation bottleneck, Task<T> is simpler for callers.10 Because the first Interlocked.Exchange() on disposeStarted already guarantees single entry, a second atomic exchange when clearing the broker reference was not used.
GC.SuppressFinalize() was not included in this sealed example because there is no finalizer and no unmanaged resource is directly owned. For inheritable types or types with a finalizer, Microsoft's async dispose pattern should be applied separately.1
TypeScript
This targets TypeScript 5.2 or later, which supports the using/await using syntax.2
export type RenderSlotToken = Readonly<{
slotId: string;
leaseId: string;
}>;
export type RenderSlotBroker = Readonly<{
acquireAsync: (
signal?: AbortSignal,
) => Promise<RenderSlotToken>;
releaseAsync: (
token: RenderSlotToken,
) => Promise<void>;
}>;
export class RenderSlotLease implements AsyncDisposable
{
readonly #token: RenderSlotToken;
#broker: RenderSlotBroker | undefined;
#disposeStarted = false;
private constructor(
broker: RenderSlotBroker,
token: RenderSlotToken,
)
{
this.#broker = broker;
this.#token = token;
}
public static async acquireAsync(
broker: RenderSlotBroker,
signal?: AbortSignal,
): Promise<RenderSlotLease>
{
signal?.throwIfAborted();
const token = await broker.acquireAsync(signal);
// A token returned successfully by the broker is a contract that it has already been validated.
return new RenderSlotLease(
broker,
token,
);
}
public getSlotId(): string
{
this.#ensureActive();
return this.#token.slotId;
}
public async [Symbol.asyncDispose](): Promise<void>
{
if (this.#disposeStarted) {
return;
}
this.#disposeStarted = true;
const broker = this.#broker;
this.#broker = undefined;
if (broker === undefined) {
return;
}
await broker.releaseAsync(this.#token);
}
#ensureActive(): void
{
if (this.#disposeStarted) {
throw new Error(
"This RenderSlotLease has already been released.",
);
}
}
}Usage syntax:
await using lease =
await RenderSlotLease.acquireAsync(
broker,
signal,
);
const slotId = lease.getSlotId();In await using, the leading await says: wait for [Symbol.asyncDispose]() when the scope ends. The await on the right does something else, it awaits the Promise the acquisition function returned so the actual disposable object lands in the variable. So if the acquisition function returns a Promise, you need a second await on the right as well.
Compiling is not the same as the runtime being ready. Check whether the target runtime provides Symbol.asyncDispose, and drop in a compatible polyfill if it does not. Check SuppressedError separately if you run native Explicit Resource Management as-is or have code that references the global constructor directly.
That said, the helper TypeScript emits for ES2022 and below includes a fallback for when the SuppressedError global is absent, so a global polyfill is not always required solely for downleveled using and await using. AbortSignal.throwIfAborted() is also a separate runtime API. Do not assume that syntax support, type libraries, and runtime capabilities are all bundled together.2
Python
The code below uses typing.Self, so it targets Python 3.11+.
from __future__ import annotations
from collections.abc import AsyncIterator
from contextlib import (
AbstractAsyncContextManager,
asynccontextmanager,
)
from dataclasses import dataclass
from types import TracebackType
from typing import Protocol, Self
@dataclass(frozen=True, slots=True)
class RenderSlotToken:
slot_id: str
lease_id: str
class RenderSlotBroker(Protocol):
async def acquire(
self,
) -> RenderSlotToken:
...
async def release(
self,
token: RenderSlotToken,
) -> None:
...
class RenderSlotLease(
AbstractAsyncContextManager["RenderSlotLease"]
):
def __init__(
self,
broker: RenderSlotBroker,
token: RenderSlotToken,
) -> None:
self._broker: RenderSlotBroker | None = broker
self._token = token
self._dispose_started = False
@classmethod
async def acquire(
cls,
broker: RenderSlotBroker,
) -> Self:
token = await broker.acquire()
# A token that the broker returns successfully is a contract guaranteeing that it has already been validated.
return cls(broker, token)
async def __aenter__(
self,
) -> Self:
self._ensure_active()
return self
async def __aexit__(
self,
exception_type: type[BaseException] | None,
exception: BaseException | None,
traceback: TracebackType | None,
) -> bool:
del exception_type
del exception
del traceback
await self.aclose()
return False
async def aclose(self) -> None:
if self._dispose_started:
return
self._dispose_started = True
broker = self._broker
self._broker = None
if broker is None:
return
await broker.release(self._token)
def get_slot_id(self) -> str:
self._ensure_active()
return self._token.slot_id
def _ensure_active(self) -> None:
if self._dispose_started:
raise RuntimeError(
"This RenderSlotLease has already been released."
)
@asynccontextmanager
async def render_slot_scope(
broker: RenderSlotBroker,
) -> AsyncIterator[RenderSlotLease]:
# Acquisition and cleanup registration are both completed within a single `__aenter__` boundary.
lease = await RenderSlotLease.acquire(broker)
try:
yield lease
finally:
await lease.aclose()
Usage syntax:
async with render_slot_scope(broker) as lease:
slot_id = lease.get_slot_id()Python's async with awaits __aenter__() and __aexit__(). If __aexit__() returns False, whatever the block raised propagates unchanged.
The current straightforward RenderSlotLease.__aenter__() does not suspend internally, so merely having no code between the acquisition statement and async with does not immediately cause a cancellation leak. However, if the acquired lease is exposed outside the context first and an await is later added between the two statements, or if __aenter__() begins asynchronous validation, an ownership gap arises. For this reason, the recommended entry point in this document is render_slot_scope(). The class's __aenter__()/__aexit__() protocol is kept for lower-level use cases that must directly own an already-acquired lease. Remote boundaries where an acquire response itself can be lost are not resolved by this structure alone; that responsibility falls on the broker's lease TTL and idempotent release protocol.
Note that async with calling __aexit__() is a different matter from the cleanup coroutine being uncancellable.
The await broker.release(...) in the code above can also be interrupted if cancellation is delivered to the task again. If a broker requires release to complete without fail, you should create a separate cleanup task, maintain a strong reference to it, and combine asyncio.shield() with a dedicated timeout. Keep in mind that shield() does not make the caller's await itself immune to cancellation, so the broker policy must also cover how to retrieve the outcome (completion or failure) of the internal cleanup task after cancellation is received.11
3. Call Site
The Renderer never learns how the slot goes back; the orchestration service alone manages the lease lifetime.
TypeScript call site example
export type RenderJob = Readonly<{
jobId: string;
sourceKey: string;
outputKey: string;
}>;
export type RenderReceipt = Readonly<{
jobId: string;
outputKey: string;
}>;
export type Renderer = Readonly<{
renderAsync: (
job: RenderJob,
slotId: string,
signal?: AbortSignal,
) => Promise<RenderReceipt>;
}>;
export class RenderJobService
{
readonly #broker: RenderSlotBroker;
readonly #renderer: Renderer;
public constructor(
broker: RenderSlotBroker,
renderer: Renderer,
)
{
this.#broker = broker;
this.#renderer = renderer;
}
public async executeAsync(
job: RenderJob,
signal?: AbortSignal,
): Promise<RenderReceipt>
{
validateJob(job);
await using lease =
await RenderSlotLease.acquireAsync(
this.#broker,
signal,
);
return await this.#renderer.renderAsync(
job,
lease.getSlotId(),
signal,
);
}
}
function validateJob(job: RenderJob): void
{
if (!isValidIdentifier(job.jobId)) {
throw new RangeError(
"The jobId format is invalid.",
);
}
if (job.sourceKey.length === 0
|| job.outputKey.length === 0) {
throw new RangeError(
"The input and output keys cannot be empty.",
);
}
}
function isValidIdentifier(value: string): boolean
{
return /^[A-Za-z0-9_.:-]{1,128}$/.test(value);
}The return await here is not a matter of taste.
Return just the Promise, as in return this.#renderer.renderAsync(...), and the function leaves the scope, so disposal may start while the renderer's async work is still using the slot. The Promise has to settle inside the scope before the lease goes back, which makes the await here part of the lifetime boundary.
Note also that await using itself does not await the acquisition Promise on the right-hand side on your behalf.2
Separation of concerns:
API Boundary
= RenderJob input validation
RenderJobService
= acquire lease
→ invoke renderer
→ end scope
RenderSlotLease
= represents process-local ownership of a slot
= does not double-start broker cleanup entry point
RenderSlotBroker
= remote coordinator I/O
= handles release timeout and protocol
Renderer
= actual GPU work execution
= no responsibility for slot return
Central Policy Handler
= acquisition failures
= rendering failures
= slot release failures
= classifies cancellation vs. timeout
= preserves both body errors and cleanup errors per language-specific rulesThe caller's cancellation token does reach slot acquisition and the render work. Cut the release of an already-acquired slot with that same token, though, and the resource is left behind, so it is safer to leave the release timeout and retry policy to a separate cleanup policy inside the broker.
The acquisition phase also has a window the scope guard cannot reach.
coordinator completes slot allocation
→ response lost on the network
→ client's acquire times out
→ lease object is never createdThe client has no token to release, while the server still holds a lease. The factory's try/finally cannot fix that; you need an acquire request id, the coordinator's lease TTL, a heartbeat and an orphan reaper. What the scope guard protects starts only after the ownership transfer has been observed to succeed.
4. Reading order
Who acquires the resource?
→ Is the acquisition success point clear?
→ Is the resource owner fixed to a single object?
→ Is the usage scope limited to a lexical block?
→ Is the resource released on normal completion, return, and exceptions?
→ If release is asynchronous, does it await completion?
→ Is double release a no-op?
→ Does it block resource access after release starts?
→ Does caller cancellation NOT invalidate cleanup?
→ Are cleanup failures propagated to the central policy layer?The first thing to check is not whether a close() method exists. It is whether every acquired object is consumed inside a scope protocol.
5. Boundaries and misconceptions
These are the resources an async scope guard fits.
Async DB connection and transaction
Remote task slot
Distributed semaphore permit
Temporary object-storage upload session
Async message consumer
Buffered writer requiring flushPlain memory objects need no dispose protocol. A garbage collector reclaims object memory, but it does not hand back an external connection or a remote lease at the point your work needs it back. Async dispose is a contract for explicit resource cleanup, not for freeing memory.
Do not mix cleanup with commit
A render slot calls the same release whether the body succeeded or not; a transaction and an upload session are different.
DB transaction
Success path → explicit CommitAsync
Exception or incomplete scope termination → RollbackAsync or Dispose
Multipart upload
Success path → CompleteAsync
Exception or incomplete scope termination → AbortAsyncIf DisposeAsync() also performs the commit that means business success, a path where the body failed halfway can still firm up a partial result. The safe default is to commit explicitly only on success and to let the cleanup of an uncommitted scope fall through to rollback/abort.
Python's __aexit__() receives the body's exception information as arguments, while C#'s DisposeAsync() and ECMAScript's [Symbol.asyncDispose]() receive nothing like that. If cleanup behavior has to differ by whether the body succeeded, do not leave the guess to the language's dispose hook, expose a state transition such as CommitAsync() in the API.
Do not release resources you do not own
Remember that the two forms below do not mean the same thing.
Receives the broker via constructor injection
→ the broker's lifetime is owned by the external composition root
→ the lease must not dispose the broker itself
Acquires a token from the broker
→ the lease owns responsibility for returning the token
→ must release it when the scope exitsLet one operation close a singleton client or connection pool the DI container manages, and other requests break with it.
Sequential duplicate Dispose and concurrent Dispose are different things
Normal scope syntax calls it once, but a defensive resource implementation is safer off treating a dispose that arrives after completion as a no-op.
First Dispose
→ Ownership removed
→ Remote release
Second Dispose
→ Ownership already gone
→ No-opOrder matters: the state gets deactivated before the release starts, not after it finishes, otherwise two concurrent calls can both perform the release I/O.
The current example assumes single-owner scope. If a second dispose arrives while the first is awaiting releaseAsync(), the second just returns immediately; this is not a model where both callers observe the remote release completing or failing. To support concurrent dispose as a public API, store the first cleanup's Task/Promise/Future in a field and hand every caller the same terminal operation. A single boolean flag only blocks duplicate I/O, not completion sharing.
The C#/TypeScript/Python lease implementations in the body clear the owner reference before starting the release, so after a failed first release you cannot call Dispose again on the same lease object to retry. The lease is off-limits from that moment, and bounded retry and idempotency are the broker's problem internally. Without that policy from the broker, this implementation guarantees only at-most-one client call, not a successful remote return.
Do not swallow cleanup failures
Remote release fails too.
Rendering succeeded
→ Slot return failed
Rendering failed
→ Slot return also failedLog it and move on inside the resource type, and the coordinator's state drifts from the real state. Cleanup failures have to go up to a central policy handler: as a typed infrastructure exception in modules that use an exception policy, as a structured failure value in Result-First modules. How an original operation failure and a cleanup failure get preserved together automatically also differs by language.
Language | When both the main body and cleanup fail |
|---|---|
C++ coroutine helper | As shown in the example, store the main body error and the cleanup error as separate |
TypeScript / ECMAScript ERM |
|
C# | If dispose fails again inside |
Python | The exception from |
- Language
C++ coroutine helper
- When both the main body and cleanup fail
As shown in the example, store the main body error and the cleanup error as separate
std::exception_ptrvalues, then throw an explicitly composed error. Do not handle this in a destructor.
- Language
TypeScript / ECMAScript ERM
- Language
C#
await using- When both the main body and cleanup fail
If dispose fails again inside
finally, the cleanup exception propagates outward. The two errors are not automatically bundled into anAggregateException. If both are needed, an explicit orchestration helper must capture the body error and combine it with the disposal error.
- Language
Python
async with- When both the main body and cleanup fail
The exception from
__aexit__()becomes the current error, and the body error generally remains in the__context__chain. To treat both errors as equivalent peers, an explicit policy such asExceptionGroup/BaseExceptionGroupfrom Python 3.11 or later is required.
Do not assume that "I used scope syntax, so both errors will show up in the central handler." Check whether your logging and trace exporters actually walk aggregate, suppressed, and cause/context chains.
In a Result-First architecture, scope syntax becomes a boundary
In projects that model predictable failures as Result<Success, Failure>, cleanup failures must be values too. Exposing await using and async with directly in the application flow gets awkward here, because neither construct gives the cleanup function a slot to return a result of its own next to the block's return value. In typical implementations a faulted ValueTask from DisposeAsync(), a rejected Promise, or an exception out of __aexit__() just propagates, which leaves two error channels: a render failure as a Result, a release failure as an exception.
Four states have to be composed here.
Body | Cleanup | Final result |
|---|---|---|
Success | Success |
|
Success | Failure |
|
Failure | Success |
|
Failure | Failure |
|
- Body
Success
- Cleanup
Success
- Final result
Result.Success(receipt)
- Body
Success
- Cleanup
Failure
- Final result
Result.Failure(CleanupFailed)
- Body
Failure
- Cleanup
Success
- Final result
Result.Failure(RenderFailed)
- Body
Failure
- Cleanup
Failure
- Final result
Result.Failure(BodyAndCleanupFailed)
If DisposeAsync() keeps the cleanup failure in an internal log and completes normally, the result itself disappears. Call ReleaseAsync() once more alongside dispose, and you get a duplicate return. To hold a strict Result-First policy, one function has to own acquisition, body execution and release, and that same function assembles the final Result.
The C# example below assumes a Result pattern that closes the failure type to a single AppError inside the application.
The details of Result<T>, AppError.Cancelled(), AppError.Timeout(), AppError.Unexpected() and AppError.Combine() are yours to set against the project's types.
public readonly record struct Unit;
public interface IResultRenderSlotBroker
{
ValueTask<Result<RenderSlotToken>> AcquireAsync(
CancellationToken cancellationToken);
ValueTask<Result<Unit>> ReleaseAsync(
RenderSlotToken token,
CancellationToken cancellationToken);
}
public static class LeaseExecution
{
public static async ValueTask<Result<T>> ExecuteWithLeaseAsync<T>(
IResultRenderSlotBroker broker,
Func<string, CancellationToken, ValueTask<Result<T>>> body,
TimeSpan cleanupTimeout,
CancellationToken callerToken = default)
{
ArgumentNullException.ThrowIfNull(broker);
ArgumentNullException.ThrowIfNull(body);
if (cleanupTimeout <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(
nameof(cleanupTimeout),
"Cleanup timeout must be positive.");
}
Result<RenderSlotToken> acquired;
try
{
acquired = await broker.AcquireAsync(callerToken)
.ConfigureAwait(false);
}
catch (OperationCanceledException ex)
when (callerToken.IsCancellationRequested)
{
return Result<T>.Fail(
AppError.Cancelled("LEASE_ACQUIRE_CANCELLED", ex));
}
catch (Exception ex)
{
// This is the final boundary for runtime/third-party exceptions that the Adapter failed to convert into values.
return Result<T>.Fail(
AppError.Unexpected("LEASE_ACQUIRE_THROWN", ex));
}
if (acquired.IsFailure)
{
return Result<T>.Fail(acquired.Error);
}
RenderSlotToken token = acquired.Value;
Result<T> bodyResult;
try
{
bodyResult = await body(
token.SlotId,
callerToken)
.ConfigureAwait(false);
}
catch (OperationCanceledException ex)
when (callerToken.IsCancellationRequested)
{
bodyResult = Result<T>.Fail(
AppError.Cancelled("LEASE_BODY_CANCELLED", ex));
}
catch (Exception ex)
{
// Business failures should already arrive as `Result`. What gets caught here are unexpected exceptions.
bodyResult = Result<T>.Fail(
AppError.Unexpected("LEASE_BODY_THROWN", ex));
}
Result<Unit> cleanupResult;
using (var cleanupCts =
new CancellationTokenSource(cleanupTimeout))
{
try
{
cleanupResult = await broker.ReleaseAsync(
token,
cleanupCts.Token)
.ConfigureAwait(false);
}
catch (OperationCanceledException ex)
when (cleanupCts.IsCancellationRequested)
{
cleanupResult = Result<Unit>.Fail(
AppError.Timeout("LEASE_CLEANUP_TIMEOUT", ex));
}
catch (Exception ex)
{
cleanupResult = Result<Unit>.Fail(
AppError.Unexpected("LEASE_CLEANUP_THROWN", ex));
}
}
if (bodyResult.IsSuccess && cleanupResult.IsSuccess)
{
return bodyResult;
}
if (bodyResult.IsFailure && cleanupResult.IsSuccess)
{
return bodyResult;
}
if (bodyResult.IsSuccess && cleanupResult.IsFailure)
{
return Result<T>.Fail(cleanupResult.Error);
}
return Result<T>.Fail(
AppError.Combine(
"LEASE_BODY_AND_CLEANUP_FAILED",
bodyResult.Error,
cleanupResult.Error));
}
}The try/catch in this function has a narrow job. Predictable business failures arrive as Result from the start; the adapter's job is to catch at the edge only what a runtime, a third-party library or a framework callback that knows nothing of your contracts throws, turn that into AppError, and hand values up to the application layer. Ban try/catch literally across the whole repository and the moment an unexpected exception escapes the body, cleanup is skipped with it.
For cancellation exceptions the catch order and the filters carry meaning. An acquire or body cancelled by the caller token stays Cancelled; an expired cleanup-only token stays Timeout. Grouping an OperationCanceledException from some other token under the same meaning hides the cause, so that one goes on to the unexpected-exception boundary below.
That said, do not demote every exception into an Unknown Result. Recover a programmer error, a broken invariant, or a state where the process can no longer be trusted as if it were an ordinary business failure, and the incident goes into hiding. Which exceptions become AppError and which get re-thrown after cleanup is what the project's failure policy decides. Cancellation is the same: if user cancellation is a normal state, turn it into a Cancelled Result; if the framework demands a cancellation exception, convert back outside the boundary.
C++ follows the same structure. The earlier std::exception_ptr-based example is an implementation for the exception policy. If you are using C++23, you can change the return type to std::expected<RenderReceipt, LeaseExecutionFailure>; for C++20 projects, you can use your own Result<T, E> or a well-tested expected implementation. TypeScript and Python can each provide an orchestration function that returns Promise<Result<T>> or Awaitable[Result[T]]. Regardless of the implementation, every exit path after acquire is merged with the cleanup result and returned to the caller.13
The selection criteria need not be more than this.
Project error policy | Recommended approach |
|---|---|
Treat cleanup failures as exceptions |
|
Cleanup failures are branching targets for the caller | A Result-composing function such as |
Like a transaction, success requires a separate commit | Explicit commit/rollback state transitions inside the Result-composing function |
- Project error policy
Treat cleanup failures as exceptions
- Recommended approach
await using,async with, C++ coroutine bracket
- Project error policy
Cleanup failures are branching targets for the caller
- Recommended approach
A Result-composing function such as
ExecuteWithLeaseAsync<T>
- Project error policy
Like a transaction, success requires a separate commit
- Recommended approach
Explicit commit/rollback state transitions inside the Result-composing function
A Result does not make the remote effect any more certain. If the release response is lost, Result.Failure(Timeout) still cannot tell you whether the release landed on the server. For that you need the leaseId, idempotent release, timeout and TTL from earlier, as before.
Here the timeout in CancellationTokenSource(cleanupTimeout) is a time budget that assumes ReleaseAsync() observes the token cooperatively. It does not force-terminate operations that ignore the token, and a timeout does not mean the remote release was not applied: the server-side TTL and idempotent request key have to cover the final recovery boundary.
Personal note: since the 2020s, explicit error handling built around
Resulthas been spreading fast even in mainstream languages. It is less a newly invented idea than the popularization of applying sum types, long used in functional languages and Rust, to error handling. In Korea it does get consumed as a bit of a trend, admittedly.Swift 5.0 added
Result<Success, Failure>, and C++23 brought instd::expected<T, E>for much the same job. TypeScript's discriminated union and Kotlin's sealed class can model errors in the same direction, so they are worth learning.In a library you intend to reuse, or at a domain boundary, naming the error kinds with
Result<T, E>is better. At a concrete application assembly layer, aResult<T>alias withEpinned to a commonAppErroris often all you need, though flattening error types into one too early makes it hard for callers to tell a domain failure they can handle from a system fault.Honestly, this one is for interviews; you can just say you do it because everyone else does.
Scope guard cannot prevent process termination
In the following cases the cleanup code does not run at all, or it runs and the remote effect still cannot be confirmed.
- Forced process termination
- Device power cutoff
- runtime crash
- Network disconnection: cleanup was invoked, but whether it took effect on the remote side is unknownFor a remote lease, the coordinator needs an expiry, a heartbeat or an orphan cleanup policy of its own. A scope guard only makes normal control flow safe; it does not stand in for fault recovery in a distributed system.
Do not accidentally suppress exceptions in Python
Return a truthy value from __aexit__() and Python treats the body exception as handled. A context manager that only releases a resource should normally return False so the original exception keeps propagating; Python's async with semantics also decide re-raise from __aexit__()'s return value.
Ways production can fail:
Calling `release` only on the success path
Fire-and-forgetting `cleanup` without awaiting it
Canceling all the way through `release` immediately via caller cancellation
Allowing the token to remain accessible externally after `dispose`
Duplicate `dispose` calls triggering remote `release` repeatedly
A lease shutting down the broker it does not own
Swallowing cleanup errors with only a log entry
Expecting the finalizer or GC to reclaim resources in a timely manner
`acquire` returns a token, then validation in the factory fails so the guard is never created
Assuming the remote `release` has exactly-once semantics
Sharing a lease across multiple tasks while one side disposes it first
Accidentally returning `True` from `__aexit__` in Python
Not verifying `Symbol.asyncDispose` support in the TypeScript runtime
Blocking the event loop in a C++ destructor to wait for async cleanup
Launching a cleanup coroutine as detached in a C++ destructor, losing its completion and any errors
Passing reference parameters to a C++ coroutine, causing temporaries to dangle
Attempting `co_await` inside a C++ `catch` handler, making cleanup recovery fail to compile
Placing the `co_await` that rolls back cleanup state outside the error-collection block, causing body errors to be lost
In Result-First code, capturing only body failures as values while leaving cleanup failures as exceptions
`DisposeAsync` swallowing cleanup failures, making it appear as though the Result flow has been honored6. Incorrect Example
async function renderJobBadAsync(
job: RenderJob,
broker: RenderSlotBroker,
renderer: Renderer,
signal?: AbortSignal,
): Promise<RenderReceipt>
{
const token = await broker.acquireAsync(signal);
const receipt = await renderer.renderAsync(
job,
token.slotId,
signal,
);
await broker.releaseAsync(token);
return receipt;
}When rendering fails, the flow goes like this.
acquire succeeded
→ render failed
→ function exits immediately
→ release never executesWhy this is bad:
Release exists only on the success path.
Every new `return` site introduces the risk of a missed release.
The caller must manage ownership of the token directly.
There is no guard against double-release.
Access to the token after release cannot be prevented.
The acquisition and use scope are not reflected in the type system or syntax.A hand-written try/finally does fix it.
const token = await broker.acquireAsync(signal);
try {
return await renderer.renderAsync(
job,
token.slotId,
signal,
);
} finally {
await broker.releaseAsync(token);
}But repeat that structure across several call sites and the release policy and the duplicate defense scatter. It maintains better to have the resource type implement AsyncDisposable itself and let call sites use only await using.
7. Production Scaling
These are the core contracts to automate inside the process.
- `broker.release` called once after successful completion
- `broker.release` called once even after task failure
- Sequential re-calls after `dispose` completes still result in exactly one `broker.release` call total
- Release failure is observable by the caller
- On `acquire` failure, the guard does not fabricate a `release` call
- Lease use is rejected after `dispose` has startedThis test does not prove that release was applied exactly once to the remote coordinator. It only verifies the calling contract up to the fake broker boundary. The actual protocol, including duplicate requests, lost responses, retries after timeout, and lease expiry, must be validated separately with integration tests.
TypeScript Automated Tests
import assert from "node:assert/strict";
import test from "node:test";
class FakeRenderSlotBroker implements RenderSlotBroker
{
readonly #token: RenderSlotToken = {
slotId: "slot-1",
leaseId: "lease-1",
};
#acquireCount = 0;
#releaseCount = 0;
public constructor(
readonly failRelease = false,
) {}
public async acquireAsync(): Promise<RenderSlotToken>
{
this.#acquireCount += 1;
return this.#token;
}
public async releaseAsync(
token: RenderSlotToken,
): Promise<void>
{
assert.deepEqual(token, this.#token);
this.#releaseCount += 1;
if (this.failRelease) {
throw new Error("Slot release failure");
}
}
public getAcquireCount(): number
{
return this.#acquireCount;
}
public getReleaseCount(): number
{
return this.#releaseCount;
}
}
test("Releases the slot once on normal termination", async () =>
{
const broker = new FakeRenderSlotBroker();
{
await using lease =
await RenderSlotLease.acquireAsync(broker);
assert.equal(
lease.getSlotId(),
"slot-1",
);
}
assert.equal(broker.getAcquireCount(), 1);
assert.equal(broker.getReleaseCount(), 1);
});
test("Releases the slot even if the body fails", async () =>
{
const broker = new FakeRenderSlotBroker();
await assert.rejects(
async () =>
{
await using lease =
await RenderSlotLease.acquireAsync(broker);
assert.equal(
lease.getSlotId(),
"slot-1",
);
throw new Error("Rendering failure");
},
/Rendering failure/,
);
assert.equal(broker.getReleaseCount(), 1);
});
test("Sequential dispose after completion does not repeat the remote release", async () =>
{
const broker = new FakeRenderSlotBroker();
const lease =
await RenderSlotLease.acquireAsync(broker);
await lease[Symbol.asyncDispose]();
await lease[Symbol.asyncDispose]();
assert.equal(broker.getReleaseCount(), 1);
});
test("Rejects slot access after disposal", async () =>
{
const broker = new FakeRenderSlotBroker();
const lease =
await RenderSlotLease.acquireAsync(broker);
await lease[Symbol.asyncDispose]();
assert.throws(
() =>
{
lease.getSlotId();
},
/already disposed/,
);
});
test("Propagates release failure to the caller", async () =>
{
const broker = new FakeRenderSlotBroker(true);
await assert.rejects(
async () =>
{
await using lease =
await RenderSlotLease.acquireAsync(broker);
assert.equal(lease.getSlotId(), "slot-1");
},
/Slot release failure/,
);
assert.equal(broker.getReleaseCount(), 1);
});The TypeScript compiler config needs a library of disposable types.
{
"compilerOptions": {
"target": "ES2022",
"lib": [
"ES2022",
"ESNext.Disposable"
],
"types": [
"node"
],
"strict": true,
"noImplicitReturns": true
}
}The config above is a Node.js example, so it needs @types/node. For a browser project, add the DOM library for Web API types such as AbortSignal and otherwise fit it to the actual runtime.
In production, watch these metrics.
render_slot.acquire.count
render_slot.acquire.duration_ms
render_slot.release.count
render_slot.release.duration_ms
render_slot.release.failed.count
render_slot.active.count
render_slot.orphan_expired.countDrop a raw leaseId or slotId into a metric label and cardinality blows up. Keep per-lease tracking in structured logs or trace fields, and leave only aggregated state in metrics.
The cleanup timeout stays separate from caller cancellation.
Task cancellation
= a request to abort rendering
cleanup timeout
= additional time allowed to return the acquired slotThe broker's releaseAsync() implementation needs a short dedicated timeout and an idempotent release protocol. If the release endpoint allows retries, keep the leaseId unchanged so a duplicate return is harmless.
8. Comparison Notes: C++ / C# / TypeScript / Python
Language | Idiomatic Pattern | Key Caveats |
|---|---|---|
C++ | Synchronous RAII + coroutine-level async bracket | Destructors cannot |
C# |
| In the dispose implementation, atomically remove ownership first |
TypeScript |
| The acquisition Promise requires a separate |
Python | async context manager + | Check the return value of |
- Language
C++
- Idiomatic Pattern
Synchronous RAII + coroutine-level async bracket
- Key Caveats
Destructors cannot
co_await. Do not work around this with blocks or detached cleanup.
- Language
C#
- Idiomatic Pattern
IAsyncDisposable+await using- Key Caveats
In the dispose implementation, atomically remove ownership first
- Language
TypeScript
- Idiomatic Pattern
AsyncDisposable+await using- Key Caveats
The acquisition Promise requires a separate
await
- Language
Python
- Idiomatic Pattern
async context manager +
async with- Key Caveats
Check the return value of
__aexit__(), re-cancellation during cleanup, and exception context together
The options in the table apply when you use the exception channel each language provides. In a Result-First application, all four languages do better with acquire, body and cleanup inside one orchestration function that composes the final failure as a value.
A sealed C# resource type can implement cleanup directly in DisposeAsync(). For an inheritable type, follow Microsoft's async dispose pattern and consider a separate virtual core cleanup method.
TypeScript's await using calls and awaits [Symbol.asyncDispose]() when the scope exits. Declare several disposables and they are cleaned up in reverse order as the scope ends.
Python supports both class-based __aenter__()/__aexit__() and generator-based asynccontextmanager(). A class is clearer for a resource that needs state and protection against double release; for a plain acquire/yield/release adapter the decorator is shorter and easier.
When multiple resources must be acquired in stages, consider each language's stack-based tool as well. TypeScript has AsyncDisposableStack and Python has contextlib.AsyncExitStack.214 Both tools let you register cleanup immediately after acquisition, so that if a later acquisition fails, any already-registered resources are cleaned up in reverse order. This makes partial acquisition failures easier to handle than manually nesting multiple await using/async with blocks.
Synchronous C++ resources are firmest under destructor-based RAII. Async cleanup, though, is not automatically awaited by standard syntax, so a coroutine combinator or the framework's async scope has to own the resource from acquisition through return.
There is no need to force the same closeAsync() name on C#, TypeScript and Python. The common contract is about this much.
The scope object holds ownership of the acquired resource,
and scope exit waits until async release completes.9. Further Considerations
When the caller cancels, does cleanup get the same cancellation signal, or its own timeout?
Does the resource wrapper own the broker itself, or only the token borrowed from it?
When the body work and the cleanup fail at the same time, in what form do both errors reach the observation layer?
What idempotency contract makes it safe for the remote coordinator to receive a release request twice?
If a forced process kill skips dispose, who owns lease expiry and orphan cleanup?
With several resources acquired in nested fashion, do you need a global acquisition order to avoid deadlock?
The server allocated, but the acquire response was lost: which request id finds the orphan?
If a lease can move to another task, what ownership rule keeps dispose from racing active use?
10. Key Takeaways
Tie the acquisition and release of an async resource to a lexical scope.
Clean up synchronous C++ resources with RAII, and await async release not in the destructor but in a coroutine-level bracket.
A C++ coroutine's frame owns only the by-value parameters, and
co_awaitcannot sit inside a catch handler; collect cleanup recovery in a separatetryblock as well.C# has
await using, TypeScript hasawait using, Python hasasync with.Make a sequential Dispose that arrives after completion a no-op, and deactivate the resource before the release starts.
To support concurrent Dispose, every caller has to share the first cleanup's Task/Promise/Future.
Do not let caller cancellation unconditionally cut the cleanup of a resource that is already acquired.
Do not swallow a cleanup failure; raise it to the central policy handler.
Under a Result-First policy, the orchestration function has to fold all four body/cleanup combinations into one
Result.Even when predictable failures are handled as values, you still need an infrastructure boundary that converts or re-throws unexpected exceptions after cleanup.
A scope guard protects normal control flow; it does not stand in for a process crash or a distributed lease expiry.
A scope guard does not guarantee exactly-once effect for a remote release; that takes idempotency on the broker, retries and a TTL.
Token validation has to finish before the broker returns normally, or the slot leaks before the scope even exists.
Memory rules:
Once you acquire a resource, don't try to remember to release it.
Use it only within a scope where release follows automatically.Footnotes
- Microsoft Learn, "Implement a DisposeAsync method" and
IAsyncDisposableAPI documentation. https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-disposeasync ↩ - TypeScript 5.2 Release Notes, "
usingDeclarations and Explicit Resource Management." https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html ↩ - Python Language Reference, "The
async withstatement." https://docs.python.org/3/reference/compound_stmts.html#the-async-with-statement ↩ - cppreference, "Destructors." Destructors cannot be coroutines, and exceptions thrown from destructors during stack unwinding can lead to
std::terminate. https://en.cppreference.com/cpp/language/destructor ↩ - AWS Well-Architected Framework, "Make all responses idempotent." https://docs.aws.amazon.com/wellarchirected/2022-03-31/framework/relpreventinteractionfailureidempotent.html ↩
- cppreference, "Coroutines (C++20)." Language transformations and restrictions of C++ coroutines. https://en.cppreference.com/cpp/language/coroutines ↩
- Boost.Asio, "C++20 Coroutines Support." Covers
awaitable, per-operation cancellation,reset_cancellation_state, andthrow_if_cancelled. https://www.boost.org/doc/libs/latest/doc/html/boostasio/overview/composition/cpp20coroutines.html ↩ - ISO C++ working draft, [expr.await]. An await-expression may appear only inside the compound-statement of a function body, outside of a handler. https://eel.is/c++draft/expr.await ↩
- WG21 N4939, "C++ Extensions for Library Fundamentals, Version 3."
scope_exit,scope_fail, andscope_successare specified as Library Fundamentals TS v3 features in<experimental/scope>. https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/n4939.html ↩ - Microsoft Learn,
ValueTask<TResult>. Describes usage constraints against awaiting a single instance multiple times or consuming it redundantly alongsideAsTask(). https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.valuetask-1 ↩ - Python Standard Library,
asyncio.shield()cancellation semantics. https://docs.python.org/3/library/asyncio-task.html#shielding-from-cancellation ↩ - TC39, "ECMAScript Explicit Resource Management," specification for
AsyncDisposableandSuppressedError. https://tc39.es/proposal-explicit-resource-management/ ↩ - cppreference,
std::expected(C++23). A standard vocabulary type that holds either a success valueTor an error valueE. https://en.cppreference.com/cpp/utility/expected ↩ - Python Standard Library,
contextlib.asynccontextmanagerandAsyncExitStack. https://docs.python.org/3/library/contextlib.html ↩