Operator yield
class UserCollection { public static IEnumerable Power() { yield return "Hello world!"; } } The yield statement from .Net Reflector - transferred to C # and the Visual Studio
class UserCollection { public static IEnumerable Power() { return new ClassPower(-2); } private sealed class ClassPower : IEnumerable<object>, IEnumerator<object>, IEnumerator, IDisposable { // Поля. private int state; private object current; private int initialThreadId; // Конструктор. public ClassPower(int state) { this.state = state; this.initialThreadId = Thread.CurrentThread.ManagedThreadId; } //private bool IEnumerator.MoveNext() // Так в Рефлекторе bool IEnumerator.MoveNext() { switch (this.state) { case 0: this.state = -1; this.current = "Hello world!"; this.state = 1; return true; case 1: this.state = -1; break; } return false; } IEnumerator<object> IEnumerable<object>.GetEnumerator() { if ((Thread.CurrentThread.ManagedThreadId == this.initialThreadId) && (this.state == -2)) { this.state = 0; return this; } return new UserCollection.ClassPower(0); } IEnumerator IEnumerable.GetEnumerator() { // Так в Рефлекторе //return this.System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator(); return (this as IEnumerable<object>).GetEnumerator(); } void IEnumerator.Reset() { throw new NotSupportedException(); } void IDisposable.Dispose() { } // Свойства. object IEnumerator<object>.Current { get { return this.current; } } object IEnumerator.Current { get { return this.current; } } } } I'm interested in the line and how the author comments
this.initialThreadId = Thread.CurrentThread.ManagedThreadId; This line indicates synchronization and access to this collection as a shared resource. Why when working with a yield, the collection is perceived as a shared resource and is generally necessary in principle to work with threads?
See the picture as I understood the work of the yield operator and it can because all the yield operators put their value in this box, so maybe you need to work with threads? 