This is one way to abandon it. The reason you do not see
Cleanup goes here
printed on the console because the for loop for (int i = 0; i < colors.Length; i++) never terminates. The following describes how to enforce the cleanup code.
Here is another way. This is the preferred template for using IDisposable objects in C #. This is preferable because it will cause an IEnumerator.Dispose call, even if an exception is thrown.
using (IEnumerator<string> reader = readColors().GetEnumerator()) { reader.MoveNext(); Console.WriteLine(reader.Current); }
As for forcing the cleanup code you have to execute, you can do the following:
static IEnumerable<string> readColors() { string[] colors = { "red", "green", "blue" }; try { for (int i = 0; i < colors.Length; i++) { yield return colors[i]; } } finally { Console.WriteLine("Cleanup goes here"); } }
jason
source share