This shows you the differences between two versions of the page.
Next revision | Previous revision Last revision Both sides next revision | ||
ienumerator [2021/03/18 01:13] 73.95.178.156 created |
ienumerator [2021/03/18 15:12] 73.95.178.156 |
||
---|---|---|---|
Line 2: | Line 2: | ||
Notes on the underlying implementation of C# generators (which are used in Unity for coroutines). | Notes on the underlying implementation of C# generators (which are used in Unity for coroutines). | ||
+ | |||
+ | You can use SharpLab to view the decompiled C# from a simple generator, to help understand the transformation that is happening. Both .NET and Mono do seem to use the same compiler transformation when turning Generators into anonymous IEnumerator classes. [[https:// | ||
+ | |||
+ | ===== States ===== | ||
+ | |||
+ | Generators are compiled down into a state machine, with states for each '' | ||
+ | * 0: The generator has not yet been run. | ||
+ | * 1: The generator has paused on the first yield return. | ||
+ | * 2: The generator has paused on the second yield return. | ||
+ | * -1: The generator has finished, the generator exited early, or the generator threw an exception. | ||
+ | |||
+ | The state value is set in a field '' | ||
+ | |||
+ | <code c#> | ||
+ | [CompilerGenerated] | ||
+ | private sealed class < | ||
+ | { | ||
+ | private int <> | ||
+ | |||
+ | private object <> | ||
+ | |||
+ | public C <> | ||
+ | // snipped | ||
+ | </ | ||
+ | |||
===== Lambda function DisplayClass classes are initialized at the start of the function ===== | ===== Lambda function DisplayClass classes are initialized at the start of the function ===== | ||
Line 60: | Line 85: | ||
The lambda function is stored as a local variable ''<> | The lambda function is stored as a local variable ''<> | ||
+ | |||
+ | ===== All lambdas are piled into a single DisplayClass anonymous type, and share the same instance. ===== | ||
+ | |||
+ |