13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

170 CHAPTER 6 Implement<strong>in</strong>g iterators the easy way}}...}yield return i;DateTime stop = DateTime.Now.AddSeconds(2);foreach (<strong>in</strong>t i <strong>in</strong> CountWithTimeLimit(stop)){Console.WriteL<strong>in</strong>e ("Received {0}", i);Thread.Sleep(300);}Typically when you run list<strong>in</strong>g 6.6 you’ll see about seven l<strong>in</strong>es of output. The foreachloop term<strong>in</strong>ates perfectly normally—as far as it’s concerned, the iterator has just runout of elements to iterate over. The yield break statement behaves very much like areturn statement <strong>in</strong> a normal method.So far, so simple. There’s one last aspect execution flow to explore: how and whenf<strong>in</strong>ally blocks are executed.EXECUTION OF FINALLY BLOCKSWe’re used to f<strong>in</strong>ally blocks execut<strong>in</strong>g whenever we leave the relevant scope. Iteratorblocks don’t behave quite like normal methods, though—as we’ve seen, a yieldreturn statement effectively pauses the method rather than exit<strong>in</strong>g it. Follow<strong>in</strong>g thatlogic, we wouldn’t expect any f<strong>in</strong>ally blocks to be executed at that po<strong>in</strong>t—and<strong>in</strong>deed they aren’t.However, appropriate f<strong>in</strong>ally blocks are executed when a yield break statement ishit, just as you’d expect them to be when return<strong>in</strong>g from a normal method. 5 List<strong>in</strong>g 6.7shows this <strong>in</strong> action—it’s the same code as list<strong>in</strong>g 6.6, but with a f<strong>in</strong>ally block. Thechanges are shown <strong>in</strong> bold.List<strong>in</strong>g 6.7Demonstration of yield break work<strong>in</strong>g with try/f<strong>in</strong>allystatic IEnumerable CountWithTimeLimit(DateTime limit){try{for (<strong>in</strong>t i=1; i = limit){yield break;}yield return i;}}f<strong>in</strong>ally{5They’re also called when execution leaves the relevant scope without reach<strong>in</strong>g either a yield return or ayield break statement. I’m only focus<strong>in</strong>g on the behavior of the two yield statements here because that’swhere the flow of execution is new and different.Licensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!