14

Can a static function in a static class which uses yield return to return an IEnumerable safely be called from multiple threads?

public static IEnumerable<FooClass> FooClassObjects()
{
    foreach (FooClassWrapper obj in listOfFooClassWrappers)
    {
        yield return obj.fooClassInst;
    }
}

Will each thread that calls this always receive a reference to each object in the collection? In my situation listOfFooClassWrappers is written to once at the beginning of the program, so I don't need to worry about it changing during a call to this function. I wrote a simple program to test this, and I didn't see any indication of problems, but threading issues can be difficult to suss out and it's possible that the issue simply didn't show up during the runs that I did.

EDIT: Is yield return in C# thread-safe? is similar but addresses the situation where the collection is modified while being iterated over. My concern has more to do with multiple threads each getting only part of the collection due to a hidden shared iterator given that the class and method are both static.

Community
  • 1
  • 1
event44
  • 630
  • 5
  • 17
  • 9
    Yes. http://stackoverflow.com/questions/1379266/is-yield-return-in-c-sharp-thread-safe, https://startbigthinksmall.wordpress.com/2008/06/09/behind-the-scenes-of-the-c-yield-keyword/, http://stackoverflow.com/questions/4157771/thread-safety-of-yield-return-is-it Each thread calling `FooClassObjects.GetEnumerator()` (such as `foreach (var foo in FooClassObjects)`) will get its own enumerator, working on its own copy of the state machine that a method containing `yield return` gets compiled into. – CodeCaster Dec 14 '15 at 15:39

1 Answers1

4

Can a static function in a static class which uses yield return to return an IEnumerable safely be called from multiple threads?

The yield keyword makes the IEnumerable<T> returning method/property an iterator. When materialized, it is invoked and internally IEnumerable.GetEnumerator() is called -- which is thread-safe. This returns a single instance.

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

Additionally, this has been asked in a similar manner here.

Community
  • 1
  • 1
David Pine
  • 23,787
  • 10
  • 79
  • 107