Wouldn't threading be complicated enough?
You should download Red-Gate's Reflector utility. It will allow you to
look at the compiled output from your own program, to see how the
compiler has transformed things like iterator methods. (It does lots
more than that, but that's the useful thing it does in this context
![Smile :) :)](/styles/default/custom/smilies/smile.gif)
). You could also use the ILDASM.EXE tool, but Reflector will decompile
back to C# or other languages if you want it to, which makes it easier
to follow the code.
The short answer:
The C# compiler transforms your iterator method into a class that
implements IEnumerator<T> or IEnumerator (as appropriate), which in turn
contains a MoveNext() method that is essentially a state machine. The
compiler takes your original code, inserts labels, and then includes a
switch to handle jumping to the correct location given the current state
of your state machine.
If you're familiar with coroutines, it's sort of like that.
So, any place you write a "yield" statement, the new method will save a
state variable to remember where it was in the method, copy the value
you specified (if it's a "yield return") to the Current property, and
then return. The next time the MoveNext() method is called, it uses the
state variable to figure out where to resume execution within the method.
So…iterators don't use threading (unless you've explicitly introduced
threading into your iterator method, of course). But they definitely
use a somewhat complex mechanism.
Pete