C'è un modo in un blocco iteratore C# per fornire un blocco di codice che verrà eseguito quando termina il foreach (o naturalmente per essere interrotto), ad esempio per ripulire le risorse?'Finally' Block in Iterators
Il meglio che ho imparato è usare il costrutto using, che va bene ma ha bisogno di una classe IDisposable per fare il clean up. Ad esempio:
public static IEnumerable<string> ReadLines(this Stream stream)
{
using (StreamReader rdr = new StreamReader(stream))
{
string txt = rdr.ReadLine();
while (txt != null)
{
yield return txt;
txt = rdr.ReadLine();
}
rdr.Close();
}
}