开发者

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

开发者 https://www.devze.com 2022-12-28 04:23 出处:网络
Would be thread-safe to 开发者_开发技巧use the yield operator inside an extension method? For example:

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号