Enumerator disposal when not using using, foreach or manually calling Dispose()
When enumerating over this iterator, if the enumerator's
Dispose()
is not explicitly called, and not used within ausing
statement, would the underlying iterator remain in an open state?
Let me re-phrase that question into a form that is easier to answer.
When using
foreach
to enumerate via an iterator block that contains ausing
statement, are the resources disposed of when control leaves the loop?
Yes.
What mechanisms ensure this?
These three:
A
using
statement is just a convenient way to write atry-finally
where thefinally
disposes of the resource.The
foreach
loop is also a convenient syntax fortry-finally
, and again, thefinally
callsDispose
on the enumerator when control leaves the loop.The enumerator produced by an iterator block implements
IDisposable
. CallingDispose()
on it ensures that all thefinally
blocks in the iterator block are executed, includingfinally
blocks that come fromusing
statements.
If I avoid the
foreach
loop, callGetEnumerator
myself, and don't callDispose
on the enumerator, do I have a guarantee that thefinally
blocks of the enumerator will run?
Nope. Always dispose your enumerators. They implement IDisposable
for a reason.
Is that now clear?
If this subject interests you then you should read my long series on design characteristics of iterator blocks in C#.
http://blogs.msdn.com/b/ericlippert/archive/tags/iterators/