Using yield to iterate over a datareader might not close the connection?

后端 未结 4 1591
一生所求
一生所求 2020-12-31 07:21

Here is a sample code to retrieve data from a database using the yield keyword that I found in a few place while googling around :

public IEnumerable

        
4条回答
  •  轮回少年
    2020-12-31 07:54

    The Iterator that the compiler synthesises implements IDisposable, which foreach calls when the foreach loop is exited.

    The Iterator's Dispose() method will clean up the using statements on early exit.

    As long as you use the iterator in a foreach loop, using() block, or call the Dispose() method in some other way, the cleanup of the Iterator will happen.

提交回复
热议问题