https://startbigthinksmall.wordpress.com/2008/06/09/behind-the-scenes-of-the-c-yield-keyword/

Behind the scenes of the C# yield keyword

June 9, 2008 by Lars Corneliussen

After reading the great article about the code-saving yield keyword “Give way to the yield keyword” by Shay Friedman I thought it could be interesting to know how the yield keyword works behind the scenes.

…it doesn’t really end the method’s execution. yield return pauses the method execution and the next time you call it (for the next enumeration value), the method will continue to execute from the last yield return call. It sounds a bit confusing I think… (ShayF)

By using yield return within a method that returns IEnumerable or IEnumeratorthe language feature is activated.

Note: IEnumerable is kind of a stateless factory for Enumerators.IEnumerable.GetEnumerator() is thread safe and can be called multiple times, while the returned stateful Enumerator is just a helper for enumerating contained values once. By contract IEnumerator offers a Reset() method, but many implementations just throw a NotSupportedException.

Lets create an enumerator method that yields some Fibonacci nubmers.

public class YieldingClass
{
public IEnumerable<int> GetFibonachiSequence()
{
yield return ;
yield return ;
yield return ;
yield return ;
}
}

Note: Yield is not a feature of the .Net runtime. It is just a C# language feature which gets compiled into simple IL code by the C# compiler.

The compiler now generates a inner class with following signature (Reflector + some renaming):

[CompilerGenerated]
private sealed class YieldingEnumerator :
IEnumerable<object>, IEnumerator<object>
{
// Fields
private int state;
private int current;
public YieldingClass owner;
private int initialThreadId; // Methods
[DebuggerHidden]
public YieldingEnumerator(int state);
private bool MoveNext();
[DebuggerHidden]
IEnumerator<int> IEnumerable<int>.GetEnumerator();
[DebuggerHidden]
IEnumerator IEnumerable.GetEnumerator();
[DebuggerHidden]
void IEnumerator.Reset();
void IDisposable.Dispose(); // Properties
object IEnumerator<object>.Current
{ [DebuggerHidden] get; } object IEnumerator.Current
{ [DebuggerHidden] get; }
}
The original method GetFibonachiSequence() only returns a new instance of the YieldingEnumerator, passing the initial state –2 as well as itself as the owner.

Each enumerator holds a state indicating:

  • -2: Initialized as Enumerable. (Not yet an Enumerator)
  • -1: Closed
  • 0: Initialized as Enumerator.  
    If a new Enumerator is requested on the same instance, GetEnumerator() returns another new instance of YieldingEnumerator.
  • 1-n: Index of the yield return in the original GetFibonachiSequence()method. In case of nested enumerators or other more complex scenarios one yield return consumes more than one index.

The content of GetFibonachiSequence() is translated into YieldingEnumerator.MoveNext().

In our very simple scenario the code looks like this:

bool MoveNext()
{
switch (state)
{
case :
state = -;
current = ;
state = ;
return true; case :
state = -;
current = ;
state = ;
return true; case :
state = -;
current = ;
state = ;
return true; case :
state = -;
current = ;
state = ;
return true; case :
state = -;
break;
}
return false;
}
Quite easy, isn’t it?

So far we easily could have created the classes and methods used to enable the yield keyword ourselves, too.

But in more complex scenarios Microsoft does some tricks, which won’t compile as C# – at least not how Reflector translates the resulting IL code.

Lets have a look at some code with a nested enumeration…

foreach(int i in new int[] {, , , , })
{
yield return i;
}
This compiles into:
private bool MoveNext()
{
try
{
switch (state)
{
case 0:
state = -1;
state = 1;
this.values = new int[] { 1, 2, 3, 5, 8 };
this.currentPositionInValues = 0;
while (this.currentPositionInValues < this.values.Length)
{
current_i = this.values[this.currentPositionInValues];
current = current_i;
state = 2;
return true;
Label_007F:
state = 1;
this.currentPositionInValues++;
}
this.Finally2();
break; case 2:
goto Label_007F;
}
return false;
}
fault
{
this.System.IDisposable.Dispose();
}
}
[/sourcecode]

Now the states 1 and 2 are used to indicate whether the enumerator actually is at some point (2), or wether it is trying to retrieve the next value (1).

Two things would not compile:

  • goto Label_007F is used to jump back into the iteration over int[] values. The C# goto statement is not able to jump into another statements context. But in IL this is totally valid as a while statement in MSIL is nothing but some gotos either.
  • The fault is proper MSIL, but not supported in C#. Basically it acts as a finally which just is executed in case of an error.

Attention: As in anonymous delegates, parameters as well as local and instance variables are passed to the YieldingEnumerator only once. Read this great post on this: Variable Scoping in Anonymous Delegates in C#

Thanks for your attention!

Behind the scenes of the C# yield keyword(转)的更多相关文章

  1. What is the use of c# “Yield” keyword ?

    What is the use of c# “Yield” keyword ? “Yield keyword helps us to do custom stateful iteration over ...

  2. What is the yield keyword used for in C#?

    What is the yield keyword used for in C#? https://stackoverflow.com/a/39496/3782855 The yield keywor ...

  3. 【转向Javascript系列】深入理解Generators

    随着Javascript语言的发展,ES6规范为我们带来了许多新的内容,其中生成器Generators是一项重要的特性.利用这一特性,我们可以简化迭代器的创建,更加令人兴奋的,是Generators允 ...

  4. .NET中的yield关键字

    浅谈yield http://www.cnblogs.com/qlb5626267/archive/2009/05/08/1452517.html .NET中yield关键字的用法 http://bl ...

  5. Python关键字yield详解以及Iterable 和Iterator区别

    迭代器(Iterator) 为了理解yield是什么,首先要明白生成器(generator)是什么,在讲生成器之前先说说迭代器(iterator),当创建一个列表(list)时,你可以逐个的读取每一项 ...

  6. [Python学习笔记-005] 理解yield

    网络上介绍yield的文章很多,但大多讲得过于复杂或者追求全面以至于反而不好理解.本文用一个极简的例子给出参考资料[1]中的讲解,因为个人觉得其讲解最为通俗易懂,读者只需要对Python的列表有所了解 ...

  7. Python yield解析

    Pyhton generators and the yield keyword At a glance,the yield statement is used to define generators ...

  8. yield return,yield break

    转自, http://www.cnblogs.com/kingcat/archive/2012/07/11/2585943.html yield return 表示在迭代中下一个迭代时返回的数据,除此 ...

  9. Understanding Asynchronous IO With Python 3.4's Asyncio And Node.js

    [转自]http://sahandsaba.com/understanding-asyncio-node-js-python-3-4.html Introduction I spent this su ...

随机推荐

  1. Spring Boot☞ 统一异常处理

    效果区:  代码区: package com.wls.integrateplugs.exception.dto; public class ErrorInfo<T> { public st ...

  2. git 进阶操作

    1.blame git blame +文件名,可以查看到某个文件每一行最近一次是由谁编辑修改的.-L 22,33 选项可以制定 2.bisect 开始git bisect:   $ git bisec ...

  3. MySQL 授权,回收权限,查看权限

    show GRANTS for root@localhost;flush privileges;SHOW PROCESSLIST; #全局授权,回收权限GRANT ALL ON *.* TO 'tes ...

  4. CodeForces 339C Xenia and Weights(暴力求解DFS)

    题意:给定 1-10的某几种砝码,给定的每种有无穷多个,然后放 m 个在天平上,要满足,相邻的两次放的砝码不能是同一种,然后是在天平两端轮流放,并且放在哪一个托盘上,那么天平必须是往哪边偏. 析:这个 ...

  5. 手机SLAM开发

    ...惯性定位 由简入繁 保留JPG文件. 回环 建模

  6. 我的CSS3学习笔记

    1.元字符使用: []: 全部可选项 ||:并列 |:多选一 ?: 0个或者一个 *:0个或者多个 {}: 范围 2.CSS3属性选择器: E[attr]:存在attr属性即可: E[attr=val ...

  7. 简述各大 Linux 发行版,有主观,不完全,望见谅

    只罗列当前热门的linux发行版 更多关于 Linux 以及 Linux 衍生版的内容可以参阅 中文wiki Debian 系 Debian:开源社区的代表性 linux 系统,每2年一次更新,现在的 ...

  8. 51nod1298圆与三角形——(二分法)

    1298 圆与三角形  题目来源: HackerRank 基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题  收藏  关注 给出圆的圆心和半径,以及三角形的三个顶点,问圆同 ...

  9. 前端技术俗语js

    注:原文是英文,本文是我翻译的.有人把我翻译的内容原文照抄,放到他自己的专栏,搞得有人问我是不是我抄袭了……请支持我的劳动成果,花了两个小时翻译的,谢谢.转载请注明译者为方应杭. 嘿,我最近接到一个 ...

  10. web_custom_request函数详解【摘抄】

    本次摘抄自:http://www.cnblogs.com/yezhaohui/p/3280239.html web_custom_request()函数是一个可以用于自定义http请求的“万能”函数, ...