How yield return works in c#

泪湿孤枕 提交于 2019-12-23 12:28:39

问题


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.

来源:https://stackoverflow.com/questions/22215210/how-yield-return-works-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!