【发布时间】:2010-11-27 05:06:21
【问题描述】:
是否有适当的方法从 foreach 中中断,以便 IEnumerable 知道我已经完成并且应该清理。
考虑以下代码:
private static IEnumerable<Person> getPeople()
{
using (SqlConnection sqlConnection = new SqlConnection("..."))
{
try
{
sqlConnection.Open();
using (SqlCommand sqlCommand = new SqlCommand("select id, firstName, lastName from people", sqlConnection))
{
using (SqlDataReader reader = sqlCommand.ExecuteReader())
{
while (reader.Read())
yield return new Person(reader.GetGuid(0), reader.GetString(1), reader.GetString(2));
}
}
}
finally
{
Console.WriteLine("finally disposing of the connection");
if (sqlConnection.State == System.Data.ConnectionState.Open)
sqlConnection.Close();
}
}
}
如果他的消费者没有从 foreach 中中断,那么一切都很好,阅读器将返回 false,while 循环将结束并且函数清理数据库命令和连接。但是如果调用者在我完成之前从 foreach 中中断会发生什么?
【问题讨论】: