Prev | Current Page 331 | Next

Jon Skeet

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

5 Listing 6.7
shows this in action??”it??™s the same code as listing 6.6, but with a finally block. The
changes are shown in bold.
static IEnumerable CountWithTimeLimit(DateTime limit)
{
try
{
for (int i=1; i <= 100; i++)
{
if (DateTime.Now >= limit)
{
yield break;
}
yield return i;
}
}
finally
{
5 They??™re also called when execution leaves the relevant scope without reaching either a yield return or a
yield break statement. I??™m only focusing on the behavior of the two yield statements here because that??™s
where the flow of execution is new and different.
Listing 6.7 Demonstration of yield break working with try/finally
171 C# 2: simple iterators with yield statements
Console.WriteLine ("Stopping!");
}
}
...
DateTime stop = DateTime.Now.AddSeconds(2);
foreach (int i in CountWithTimeLimit(stop))
{
Console.WriteLine ("Received {0}", i);
Thread.Sleep(300);
}
The finally block in listing 6.7 is executed whether the iterator block just finishes by
counting to 100, or whether it has to stop due to the time limit being reached. (It
would also execute if the code threw an exception.) However, there are other ways we
might try to avoid the finally block from being called??¦ let??™s try to be sneaky.
We??™ve seen that code in the iterator block is only executed when MoveNext is
called. So what happens if we never call MoveNext? Or if we call it a few times and then
stop? Let??™s consider changing the ???calling??? part of listing 6.


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