开发者

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


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜