¿Hay una forma adecuada de romper con un foreach tal que el IEnumerable <> sepa que he terminado y debería limpiarlo?una preocupación acerca del retorno de rendimiento y la ruptura de un foreach
Considere el siguiente código:
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();
}
}
}
Si el consumidor no se rompe desde el foreach continuación Everthing está muy bien y el lector volverá falso, el willend bucle while y la función limpia el comando de base de datos y la conexión . Pero, ¿qué sucede si la persona que llama se separa del foreach antes de que yo termine?
ver también http://stackoverflow.com/questions/1400146/are-there-any-pitfalls-to-using-an-ienumerablet-return-type-for-sql-data/1400195# 1400195 –