yield
basically makes an IEnumerable<T>
method behave similarly to a cooperatively (as opposed to preemptively) scheduled thread.
yield return
is like a thread calling a "schedule" or "sleep" function to give up control of the CPU. Just like a thread, the IEnumerable<T>
method regains controls at the point immediately afterward, with all local variables having the same values as they had before control was given up.
yield break
is like a thread reaching the end of its function and terminating.
People talk about a "state machine", but a state machine is all a "thread" really is. A thread has some state (I.e. values of local variables), and each time it is scheduled it takes some action(s) in order to reach a new state. The key point about yield
is that, unlike the operating system threads we're used to, the code that uses it is frozen in time until the iteration is manually advanced or terminated.