使用“yield”是线程安全的吗?扩展方法内的运算符?
在扩展方法中使用yield 运算符是否是线程安全的?
例如:
public static IEnumerable<CartItem> GetItems( this Cart cart )
{
{
while( cart.hasNext() )
yield return cart.GetNextItem( );
}
}
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( );
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不太确定你的意思,但yield return本质上会导致函数生成状态机包装类并返回该类的实例。每个收益率返回都是来自状态机的返回。调用您的方法返回的单个实例不是线程安全的(您不能从多个线程同时迭代它),但多个调用将生成单独的实例。这些单独的实例可以由多个线程使用,在这种情况下,线程安全性由枚举器使用的类的线程安全性决定(在您的情况下,是
cart
的方法。)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.)