Sub topic 13
Designing Your Own Disposable Resources
This chapter assumes you already know the disposable protocol, using and await using, and the basic DisposableStack methods from earlier chapters. Here the focus moves from consuming resources to writing them. A well-designed disposable behaves predictably when it is disposed twice, when someone uses it after cleanup, and when its setup fails partway through.
The Lifecycle of a Resource
Every disposable has two states that matter: open and disposed. Your methods should check that state, and your dispose method should change it exactly once.
A Class-Based Resource
The class below follows the common conventions. It keeps a private flag, makes dispose idempotent, rejects use after disposal, and keeps a familiar close() method alongside Symbol.dispose so callers who manage cleanup by hand still have an obvious method to call.
class LogFile {
#name;
#closed = false;
constructor(name) {
this.#name = name;
console.log(`open ${name}`);
}
write(line) {
if (this.#closed) throw new Error(`${this.#name} is closed`);
console.log(`${this.#name}: ${line}`);
}
close() {
if (this.#closed) return; // idempotent
this.#closed = true;
console.log(`close ${this.#name}`);
}
[Symbol.dispose]() {
this.close();
}
}
{
using log = new LogFile("app.log");
log.write("started");
log.close(); // early manual close is fine
} // Symbol.dispose runs again and does nothingIdempotence matters because ownership is often shared loosely. A resource might be closed by hand, then disposed again by using or by a stack, and neither call should fail.
A Factory for Registrations
Many resources are really registrations: event listeners, subscriptions, timers. For these, a function that returns a small disposable object is usually simpler than a class.
function listen(target, type, handler) {
target.addEventListener(type, handler);
let active = true;
return {
[Symbol.dispose]() {
if (!active) return;
active = false;
target.removeEventListener(type, handler);
},
};
}
const bus = new EventTarget();
{
using _sub = listen(bus, "ping", () => console.log("got ping"));
bus.dispatchEvent(new Event("ping")); // got ping
}
bus.dispatchEvent(new Event("ping")); // nothing: listener removedThe subscription stays in effect only inside the block where it was declared, so it cannot be left behind by mistake.
Composite Resources That Own Children
When a resource owns other resources, build it with a DisposableStack. The using stack plus move() pattern protects the constructor. If the second child throws during setup, the first one is still cleaned up.
class Session {
#stack;
constructor() {
using stack = new DisposableStack();
this.audit = stack.use(new LogFile("audit.log"));
this.errors = stack.use(new LogFile("errors.log"));
this.#stack = stack.move(); // setup succeeded: keep the children
}
[Symbol.dispose]() {
this.#stack.dispose(); // reverse order, already idempotent
}
}
{
using session = new Session();
session.audit.write("login");
}
// close errors.log
// close audit.logDesign Checklist
| Guideline | Reason |
|---|---|
| Make dispose idempotent | Manual closes and stacks may call it more than once |
| Throw on use after dispose | Fails loudly instead of corrupting state |
| Avoid throwing from dispose | Cleanup errors become `SuppressedError` chains that are hard to read |
| Pick one protocol per resource where possible | Implement `Symbol.asyncDispose` only when cleanup really needs to await |
| Use an internal `DisposableStack` for children | Gives reverse-order cleanup and safe partial setup |
| Keep a named method like `close()` | Callers without `using` support can still clean up |
Exercise
In the Session constructor, what happens if new LogFile("errors.log") throws, and why would a plain this.#stack = new DisposableStack() without using behave differently?
Show answer
With using stack, the exception leaves the constructor's block, so the stack is disposed and closes audit.log before the error propagates. With a plain field assignment, nothing disposes the stack because the caller never receives a Session object, so audit.log would leak.
Exercise
Why does the listen factory track an active flag even though removeEventListener is harmless to call twice?
Show answer
The flag keeps the disposal contract explicit and consistent across all resources. It also protects against side effects when the underlying API is not safe to call twice, and it makes later additions (such as logging or counters) run only once.