IEnumerable <が完了したことを知っているので、foreachから切り離す適切な方法があります。foreachからの歩留まり復帰と懸念について
次のコードを考えてみましょう:
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();
}
}
}
彼は、消費者は、その後everthingは罰金で、読者はfalseを返しますforeachのから壊れていない場合は、whileループのwillendと機能がデータベースコマンドとの接続をクリーンアップ。しかし、終了する前に発信者がforeachから壊れた場合はどうなりますか?
もhttp://stackoverflow.com/questions/1400146/are-there-any-pitfalls-to-using-an-ienumerablet-return-type-for-sql-data/1400195#を参照してください1400195 –