Uninomicon

Documenting the dark corners of the Unity Engine.

User Tools

Site Tools


ienumerator

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
ienumerator [2021/03/18 01:18]
73.95.178.156
ienumerator [2021/04/29 19:10] (current)
uninomiconadmin
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://sharplab.io/#v2:EYLgtghgzgLgpgJwDQBMQGoA+ABATARgFgAobABgAJt8A6AYQHsAbJuAYxgEsGA7KAbhLYAzFVwU6FAN4kKcigHoFIipx4wKAD0HF5FWft3yVASQCiPAK5hEEGAwQUAsgAoAlNIN651fFQDsFPg63sb4ftiBuCGhVOEBFMIxob4JACzJFAC+XoZ6phbWtvaOACpwsC7YAKwAPMAMzAB8FABmljxsHjJGKfGRbR1s7pk5xFlAA===|example]]
 +
 +===== States =====
 +
 +Generators are compiled down into a state machine, with states for each ''yield return'' point. ie:
 +  * 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 ''%%private int <>1__state%%'' on the generated IEnumerator class:
 +
 +<code c#>
 +    [CompilerGenerated]
 +    private sealed class <M>d__0 : IEnumerator<object>, IDisposable, IEnumerator
 +    {
 +        private int <>1__state;
 +
 +        private object <>2__current;
 +
 +        public C <>4__this;
 +        // snipped
 +</code>
 +
  
 ===== 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 61: Line 86:
 The lambda function is stored as a local variable ''<>8__1'' in the generated IEnumerator class. However, the instance is created at the start of the function, not just before usage, as one might expect.  The lambda function is stored as a local variable ''<>8__1'' in the generated IEnumerator class. However, the instance is created at the start of the function, not just before usage, as one might expect. 
  
-===== All lambdas are piled into a single DisplayClass anonymous type, and share the same instance. =====+**All lambdas are piled into a single DisplayClass anonymous type, and share the same instance.**
  
  
ienumerator.1616030329.txt.gz ยท Last modified: 2021/03/18 01:18 by 73.95.178.156