August 15th, 2008

The implementation of iterators in C# and its consequences (part 4)

You can breathe a sigh of relief. Our long national nightmare is over: this is the end of CLR Week 2008. We wind down with a look back at iterators.

Michael Entin points out that you can use C# iterators to make asynchronous code easier to write. You can use C# iterators for more than simply iterating.

The automatic conversion of straight line code into a state machine is handy when you want an easy way to write, well, a state machine. It’s one of those things that’s blindingly obvious once you look at it the right way.

The transformation that the yield return statement induces on your function turns it from a boring function into an implicit state machine: When you execute a yield return, execution of your function is suspended until somebody asks your iterator the next item, at which point execution resumes at the statement after the yield return. This is exactly what you want when breaking a synchronous function into asynchronous pieces: Each time you would normally block on an operation, you instead perform a yield return, and when the operation completes, you call the MoveNext method, which resumes execution of the function until the next time it needs to wait for something and performs a yield return.

It’s so simple it’s magic.

Additional iterator-related reading:

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.