When using yield within a “using” statement, when does Dispose occur?

前端 未结 1 643
故里飘歌
故里飘歌 2021-02-07 02:04

I have a question regarding deferred execution and the disposing of data.

Consider the following example:

private IEnumerable ParseFile(str         


        
1条回答
  •  清酒与你
    2021-02-07 02:22

    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).

    0 讨论(0)
提交回复
热议问题