Asynchronous Programming With Iterators

I just saw this on the visual Studio Start page

It’s a pretty interesting video worth checking out. It seems like one of those good ideas that translate into a very small library that can be used to do powerful things.

To sum it up briefly (in case you can’t afford to watch the 20 minute long video) Jeff has realized that the state machine-esque code generated for you when you create an iterator in C# (i.e. “yield return”) is exactly the same type of code you’d need to write to comply with the standard .NET asynchronous programming model. Therefore writing your asynchronous code inside of an iterator (with help from his AsyncEnumerator class) allows you to write code in a synchronous format and rely on the C# iterator expansion capabilities to translate that into asynchronously compatible code.

As clever and interesting as this is I’m not happy about the (mis)use of the yield syntax to work around a compiler limitation. I have submitted this idea to the Boo Lang user group because this seems like the perfect example of the potential power of meta programming. In the case of C# you have some macro expansion for certain baked in keywords (using, lock, yield, etc.), and it just so happens that the expansion of the yield keywords is exactly what you need to match some other pattern but I believe you could do this in Boo in a much cleaner way.

Imagine having an actual “async” keyword and an “wait” keyword? It would do nearly the same thing but would make it all feel so much cleaner. Anyway, food for thought.


Author: justinmchase

I'm a Software Developer from Minnesota.

%d bloggers like this: