How yield return works in c#

2019-06-23 18:23发布

I have following piece of code.

public static void main(string []args)
{

  var intergers = GetCollection();

  foreach(var val in intergers)
  {
   console.writeline(val);
   }

}

public IEnumerable<int> GetCollection()
{

  yield return 10;

  var obj = new MyClass();
  obj.performLargeAction();

  yield return 1;

  var obj = new MyClass();
  obj.perform();

  yield return 2;

  console.writeline("I am finished now");  
}

Now, when I debug the code and see the foreach iteration, then I see that first time method executes till yield return 10 and then control goes back to foreach loop, on next iteration code after yield return 10 and till yield return 1 is executed and in next iteration it executes from line right after yield return 1 and till yield return and in next iteration it calls console.writeline();

So, with this behavior, I am keen to know does .net pause the execution of the method which is returning IEnumerable and save its location counter or state to the stack and next iteration again pops the location and set it to program counter or location counter and all these thing or

I have read something yield is a c# feature, so this above piece of code is converted to IL and that yield part is replaced with a class called YieldEnumerator which stores state, current and other thing. but still I could not understand its actual functioning. So, I would like to know its internal working form starting to end.

0条回答
登录 后发表回答