Prev | Current Page 330 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

However, the point is that it can all be done.
4 Note that methods taking ref or out parameters can??™t be implemented with iterator blocks.
Listing 6.6 Demonstration of yield break
Stops if our
time is up
170 CHAPTER 6 Implementing iterators the easy way
}
yield return i;
}
}
...
DateTime stop = DateTime.Now.AddSeconds(2);
foreach (int i in CountWithTimeLimit(stop))
{
Console.WriteLine ("Received {0}", i);
Thread.Sleep(300);
}
Typically when you run listing 6.6 you??™ll see about seven lines of output. The foreach
loop terminates perfectly normally??”as far as it??™s concerned, the iterator has just run
out of elements to iterate over. The yield break statement behaves very much like a
return statement in a normal method.
So far, so simple. There??™s one last aspect execution flow to explore: how and when
finally blocks are executed.
EXECUTION OF FINALLY BLOCKS
We??™re used to finally blocks executing whenever we leave the relevant scope. Iterator
blocks don??™t behave quite like normal methods, though??”as we??™ve seen, a yield
return statement effectively pauses the method rather than exiting it. Following that
logic, we wouldn??™t expect any finally blocks to be executed at that point??”and
indeed they aren??™t.
However, appropriate finally blocks are executed when a yield break statement is
hit, just as you??™d expect them to be when returning from a normal method.


Pages:
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342