C# in Depth

Cover of C# in Depth
Order now (3rd edition)

Finally blocks in iterators

Chapter 6: Implementing iterators the easy way: 6.2.3

Created: 2/24/2008
Last updated: 3/10/2008

It's worth being careful about what you put in a finally block in iterators, precisely because (as shown in the book) the finally may not be executed.

This will usually only be the case with a malicious caller - let's face it, everyone else is bound to be using foreach - which gives a hint as to the kind of code to include and the kind of code to avoid.

If you use the finally block for resource cleanup - perhaps implicitly, with a using statement - that's probably okay. If the caller doesn't call Dispose, it's no worse than them failing to call Dispose on the embedded resource.

If, however, you were to use the finally block for security purposes - for instance, to relinquish some extra rights gained earlier on - then that would be very dangerous.

Likewise it's probably a bad idea to use lock across a yield return. It's okay to acquire and release a lock in the course of the iterator block without yielding - during that time it'll be running just like a normal method - but if you return a value while holding the lock, the lock will still be held until execution comes back into the iterator block, which may be never!