What does “yield break;” do in C#?

后端 未结 8 1899
南方客
南方客 2020-11-28 01:04

I have seen this syntax in MSDN: yield break, but I don\'t know what it does. Does anyone know?

相关标签:
8条回答
  • 2020-11-28 01:28

    Here http://www.alteridem.net/2007/08/22/the-yield-statement-in-c/ is very good example:

    public static IEnumerable<int> Range( int min, int max )
    {
       while ( true )
       {
          if ( min >= max )
          {
             yield break;
          }
          yield return min++;
       }
    }
    

    and explanation, that if a yield break statement is hit within a method, execution of that method stops with no return. There are some time situations, when you don't want to give any result, then you can use yield break.

    0 讨论(0)
  • 2020-11-28 01:35

    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.

    0 讨论(0)
提交回复
热议问题