Sub topic 5
When and in What Order Resources Are Disposed
This chapter assumes you already know how using declares a resource and how an object becomes disposable through Symbol.dispose. It also assumes you are comfortable with block scoping and try/finally. The examples use the openResource helper from earlier chapters, repeated here so that each snippet runs on its own.
Disposal Happens When the Block Exits
A using resource is disposed when control leaves the block that contains its declaration. It does not matter how control leaves. All of these trigger disposal:
- The block finishes normally.
- A
returnruns inside a function body. - A
breakorcontinueleaves a loop body. - An exception is thrown and not caught inside the block.
Disposal does not happen when the variable stops being used, and it does not wait for garbage collection. The exit point is fixed by the source code, so you can see where cleanup runs by finding the closing brace.
function openResource(name) {
console.log(`open ${name}`);
return {
name,
[Symbol.dispose]() {
console.log(`close ${name}`);
},
};
}
function read() {
using res = openResource("file");
return `read from ${res.name}`;
}
console.log(read());
// open file
// close file
// read from fileThe return expression is evaluated first, while res is still open. Disposal runs next, and only then does the caller receive the value. Values you compute from a resource in a return statement are therefore safe. Returning the resource object itself is a different matter: the caller gets an object that has already been closed.
Reverse Order: Last In, First Out
When a block declares several resources, they are disposed in the reverse of their declaration order. The runtime keeps a stack for each block. Each using pushes a resource onto it, and leaving the block pops them off one at a time.
This order matches how resources usually depend on each other. If b is a transaction opened on connection a, then b has to close while a is still alive. Nested blocks follow the same rule: the inner block's resources are disposed when the inner block exits, before anything in the outer block is disposed.
Several declarators in one statement, such as using a = x(), b = y();, behave exactly like separate statements. They are also disposed b first, then a.
Only Initialized Resources Are Disposed
A resource joins the stack only after its declaration finishes successfully. If a later initializer throws, the resources declared before it are still cleaned up, and the failed one is skipped.
function openResource(name) {
if (name === "bad") throw new Error("cannot open bad");
console.log(`open ${name}`);
return { name, [Symbol.dispose]() { console.log(`close ${name}`); } };
}
try {
using a = openResource("a");
using b = openResource("bad");
using c = openResource("c");
} catch (e) {
console.log(e.message);
}
// open a
// close a
// cannot open badThe c line never runs, and b never existed, so a is the only resource closed. The cleanup finishes before the catch block runs. With hand-written try/finally you would need one nested try for each resource to get this behavior.
Common Errors
| Mistake | What actually happens |
|---|---|
| Returning the resource itself from a `using` block | The caller receives an already-disposed object |
| Declaring a dependent resource before its dependency | The dependency is disposed second, so the dependent resource closes first anyway. Declare dependencies first. |
| Expecting cleanup at the last use of the variable | Cleanup waits for the end of the block |
| Assuming a failed initializer is disposed | It was never added to the stack, so it is skipped |
Exercise
A block declares using conn = open("conn"), then using tx = open("tx"), then using log = open("log"), and then throws an error. Which close messages are printed, and in what order?
Show answer
"close log", then "close tx", then "close conn". All three declarations completed, so all three resources are on the stack, and the thrown error makes them dispose in reverse declaration order before the error reaches any outer handler.
Exercise
In the same block, suppose open("tx") throws. What is printed?
Show answer
Only "close conn". The tx resource was never created, and the log line never runs, so conn is the only resource on the stack.