A C# custom `Pairwise` operator calls `source.GetEnumerator()` directly; why does the sensor stream's `finally` never close the port when the consumer stops at `Take(1)`?
answer
- IEnumerator<T> is IDisposable
- who disposes what on early exit
- plain local, no using
- foreach disposes, manual code must
- no finalizer on iterators
basics
~20 sThe operator holds the source enumerator in a plain local and never disposes it. When Take stops early, Dispose reaches the operator's iterator but not the source's, so the source's finally never runs. Declare it with using IEnumerator<T> e = source.GetEnumerator().
solid answer
~40 s`IEnumerator<T>` derives from `IDisposable`, and disposing a compiler-generated iterator early is what runs its pending `finally` blocks. When the consumer stops, its `foreach` disposes `Take`'s enumerator, `Take` disposes the `Pairwise` iterator, and that iterator's `Dispose` runs the `finally` blocks of its own body. A plain local `IEnumerator<T> e = source.GetEnumerator();` has no `finally`, so the chain stops there: the sensor iterator is never disposed, and its `finally` that closes the port never runs. The generated iterator has no finalizer, so the garbage collector will not run it later either. The fix is `using IEnumerator<T> e = source.GetEnumerator();`, which the compiler lowers to a `try`/`finally` inside the operator; or use `foreach` over `source`, which disposes for you. .NET's own `Chunk` uses exactly that `using` line.
code
csharp · 32 linesforeach (var pair in Sensor.Stream().PairwiseLeaky().Take(1)) Console.WriteLine(pair);
Console.WriteLine("---");
foreach (var pair in Sensor.Stream().Pairwise().Take(1)) Console.WriteLine(pair);
static class Sensor
{
public static IEnumerable<int> Stream()
{
Console.WriteLine(" open port");
try { for (int t = 20; ; t++) yield return t; }
finally { Console.WriteLine(" close port"); }
}
}
static class SensorOps
{
public static IEnumerable<(T, T)> PairwiseLeaky<T>(this IEnumerable<T> source)
{
IEnumerator<T> e = source.GetEnumerator(); // never disposed
if (!e.MoveNext()) yield break;
T previous = e.Current;
while (e.MoveNext()) { yield return (previous, e.Current); previous = e.Current; }
}
public static IEnumerable<(T, T)> Pairwise<T>(this IEnumerable<T> source)
{
using IEnumerator<T> e = source.GetEnumerator(); // disposed on early exit too
if (!e.MoveNext()) yield break;
T previous = e.Current;
while (e.MoveNext()) { yield return (previous, e.Current); previous = e.Current; }
}
}go deeper
Remember that IEnumerator<T> is IDisposable and that foreach disposes the enumerator for you; manual GetEnumerator code has to do it itself.
Explain how disposal travels down a chain on early exit and how an iterator's Dispose runs its pending finally blocks.
Diagnose the leak from a finally that never runs, fix it with a using declaration, and explain why the garbage collector does not run iterator cleanup.
Treat source disposal as part of every shared operator's contract, and require a test that cuts the operator with Take(1) over a source that records its cleanup.
## Why an operator ever calls GetEnumerator by hand Most operators should just `foreach` over their source. Some cannot: `Pairwise` wants to read the first element before the loop, a `Zip`-like operator advances two sources in lockstep, and a "take until changed" operator needs to know whether another element exists before yielding. Those operators call `source.GetEnumerator()` and drive `MoveNext` and `Current` themselves, and in doing so they take on a job `foreach` normally does: **disposing the enumerator**. ## How early exit travels down a pipeline `IEnumerator<T>` inherits `IDisposable`. For an iterator, `Dispose` is not cosmetic: when an enumeration stops before the body finishes, calling `Dispose` runs the `finally` blocks (and `using` disposals) that are still pending in the body. That is how a sensor iterator written as `try { ... yield return ... } finally { ClosePort(); }` gets to close its port when nobody wants more readings. When the consumer leaves its loop, disposal flows down the chain one link at a time: 1. The consumer's `foreach` ends (after `Take` says it has no more, after a `break`, or on an exception) and its hidden `finally` disposes the enumerator it holds, the one from `Take`. 2. `Take` disposes the enumerator it took from its source, here the `Pairwise` iterator. 3. The `Pairwise` iterator's `Dispose` runs whatever `finally` blocks are pending in **its** body. 4. If the source enumerator is disposed in one of those `finally` blocks, the sensor iterator's own `finally` runs and the port closes. Step 4 only happens if the operator wrote it. With a plain local the chain is cut at step 3. ## The leaky and the correct operator ```csharp IEnumerator<T> e = source.GetEnumerator(); // leaky: nothing disposes it using IEnumerator<T> e = source.GetEnumerator(); // correct: disposed on every exit ``` The example on this page runs both versions over the same sensor iterator. The leaky one prints `open port` and the pair, and never prints `close port`; the `using` version prints `close port` right after `Take(1)` finishes. A `using` declaration is lowered to a `try`/`finally` around the rest of the block, and inside an iterator that `finally` is exactly what the iterator's `Dispose` runs on early exit. | Exit path | Plain local | `using` declaration | |---|---|---| | source runs out | not disposed | disposed | | consumer stops early (`Take`, `break`) | not disposed | disposed | | consumer or predicate throws | not disposed | disposed | ## Why the garbage collector does not rescue it The compiler-generated iterator class has no finalizer; checking its type for a declared `Finalize` method on .NET 10 finds none. So the `finally` block in the sensor iterator is ordinary code that runs only when `MoveNext` reaches it or `Dispose` is called. An abandoned iterator is simply collected, and the cleanup it promised never happens. What survives depends on what the `finally` was protecting: - A connection, port or lock released in the `finally` stays held until something else gives it up. - An OS handle wrapped in a `SafeHandle` may eventually be released by that handle's own finalizer, at an unpredictable time, but your cleanup code in the `finally` still never runs. ## Getting it right - Prefer `foreach` over `source`; it disposes for you, on every path. - When you need the enumerator, declare it with `using` on the same line you obtain it. .NET's `Chunk` does exactly this: `using IEnumerator<TSource> e = source.GetEnumerator();`. - With two sources, give each its own `using`, so the first is still disposed if obtaining the second throws. - Do not try `try { ... } catch { e.Dispose(); }`: a `catch` covers only exceptions, and `yield return` inside a `try` that has a `catch` is rejected with CS1626, "Cannot yield a value in the body of a try block with a catch clause". - Remember that the error path uses the same chain: if the consumer's loop body or a predicate throws, its `foreach` still disposes what it holds, and a `using` in the operator passes that disposal on to the source. - Test operators with a source whose `finally` records that it ran, cut by `Take(1)`; a missing record is this bug.
- Will the garbage collector eventually run the sensor iterator's `finally`?No. The compiler-generated iterator has no finalizer, so its `finally` code runs only when `MoveNext` reaches it or `Dispose` is called. An abandoned enumerator is collected with its cleanup skipped; at best a `SafeHandle` inside it is released later by its own finalizer.
- What changes when the operator reads two sources in lockstep?It owns two enumerators and must dispose both, so each gets its own `using` declaration. If the second `GetEnumerator()` throws, the first `using` still disposes the first enumerator, and when the consumer stops early both are disposed in reverse order.
- Why not dispose the enumerator in a `catch` block instead?A `catch` runs only when an exception is thrown, so early exit through `Take` or `break` would still leak. The compiler also rejects `yield return` inside a `try` block that has a `catch` clause with CS1626, so the pattern cannot even wrap the loop.
- The garbage collector will run the iterator's finally block later
- Disposing the outer iterator disposes every enumerator it obtained
- Take(1) reads to the end of the source, so the finally runs anyway
- IEnumerator<T> is not IDisposable, so there is nothing to dispose
- A try/catch around the loop is enough to dispose the enumerator