SDReyes
SDReyes

Reputation: 9954

Is thread-safe to use the 'yield' operator inside an extension method'?

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( );
        }
}

Upvotes: 4

Views: 841

Answers (1)

Dan Bryant
Dan Bryant

Reputation: 27515

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.)

Upvotes: 3

Related Questions