views:

111

answers:

1

Would be thread-safe to use the yield operator inside an extension method?

For example:

public static IEnumerable<CartItem> GetItems( this Cart cart )
{
        {
            while( cart.hasNext() )
                yield return cart.GetNextItem( );
        }
}
+2  A: 

I'm not exactly sure what you mean, but yield return essentially causes the function to generate a state machine wrapper class and returns an instance of the class. Each yield return is a return from the state machine. The individual instance returned by a call to your method would not be thread-safe (you can't iterate on it simultaneously from multiple threads), but multiple calls would generate separate instances. Those separate instances could be used by multiple threads and the thread-safety in that case is determined by the thread-safety of the classes used by the enumerator (cart's methods, in your case.)

Dan Bryant
Thanks you Dan. you have answered my question +1Anyway let me use a simpler example to clarify my point for further readers ; )
SDReyes
Thank you for updating your answer accordingly to the new example, Dan.
SDReyes