Middle · Design · Async, callbacks and cancellation ownership

How would you bound memory retained by slow asynchronous operations?

Think through your answer before opening the explanation.

Memory & GC

Reveal answer and reasoning

Acquire admission before allocating large request state. Own a registration in the operation scope, finish or cancel child work under a documented policy, and return rented buffers only after all consumers have actually stopped. A fire-and-forget callback that still uses a buffer after its parent returns creates a correctness defect even if the parent puts the array back in a pool on time.

Reachability and valid ownership are different guarantees.

For interview discussion, show both success and failure paths. Ask what happens when cancellation races completion, when a callback throws, and when a producer waits for capacity while already holding a payload. A strong answer names the current owner, the event ending its lease and the action that handles partial progress. Static callbacks can help control capture, but they cannot substitute for those lifecycle decisions.

Move the first Cancel call after the registration's using block. Predict that the callback no longer increments Calls. Keep the source alive and verify cancellation state independently. Then create two registrations and dispose only one before cancellation. Predict the exact count without claiming anything about collected memory.

Review an asynchronous method that reads a large body before awaiting admission. Draw the root path from its pending task to the body. Redesign it so the number of waiting callers and preallocated payloads is bounded, preserving cancellation and error behavior. Finally, explain why clearing a local in one method cannot release a payload still owned by a continuation or a long-lived publisher.

What a strong answer covers

  • Pending work can extend ownership beyond a method return.
  • A static callback avoids lexical capture but explicit state is still strongly owned.
  • Cancellation request, callback disposal and task completion are distinct events.

Common pitfall

Assuming a static callback retains no explicit state, or that requesting cancellation ends every outstanding lease.

Follow-up questions

  1. Can CancellationTokenRegistration.Dispose coordinate with a concurrently running callback?
  2. What happens to a large request state while a downstream task stays incomplete?

Self-review

Choose what to revisit. These marks are your own assessment and are separate from lesson completion.

Primary references

Open lesson and code ↗

← All interview questions