I have a question regarding deferred execution and the disposing of data.
Consider the following example:
private IEnumerable ParseFile(str
So we have several separate issues going on here.
First off, dealing with the using
in the iterator block. IEnumerator
extends IDisposable
. The code that generates iterator blocks is actually robust enough that any try/finally blocks (a using
results in a try/finally
block being created) results in the contents of the finally
block being called in the Dispose
method of the enumerator, if it wasn't already called. So as long as the enumerator is disposed, it won't leak the StreamReader
.
So now we ask ourselves if the enumerator is disposed. All foreach
statements will call Dispose
on the enumerator (should it implement IDisposable
). They do so even if you exit using a break
or return
statement, as well as when it finishes normally.
So you can be sure that under all circumstances the resource won't be leaked, barring the cases where nothing can be prevented from leaking (i.e. someone unpugging the machine).