C#线程安全的收益率返回值安全吗? [英] Is yield return in C# thread-safe?
问题描述
我有以下代码:
private Dictionary<object, object> items = new Dictionary<object, object>;
public IEnumerable<object> Keys
{
get
{
foreach (object key in items.Keys)
{
yield return key;
}
}
}
这是线程安全的吗?如果不是,我必须在循环或yield return
周围放一个lock
?
Is this thread-safe? If not do I have to put a lock
around the loop or the yield return
?
这是我的意思:
Thread1访问Keys
属性,而Thread2将项添加到基础字典中. Thread1是否受Thread2的添加影响?
Thread1 accesses the Keys
property while Thread2 adds an item to the underlying dictionary. Is Thread1 affected by the add of Thread2?
推荐答案
好的,我做了一些测试,结果很有趣.
OK, I did some testing and got an interesting result.
似乎与yield
关键字相比,更多的是基础集合的枚举器问题.枚举器(实际上是其MoveNext
方法)会抛出(如果正确实现)InvalidOperationException
,因为枚举已更改.根据 MoveNext方法的MSDN文档这是预期的行为.
It seems that it is more an issue of the enumerator of the underlying collection than the yield
keyword. The enumerator (actually its MoveNext
method) throws (if implemented correctly) an InvalidOperationException
because the enumeration has changed. According to the MSDN documentation of the MoveNext method this is the expected behavior.
因为通过集合进行枚举通常不是线程安全的,所以yield return
也不是线程安全的.
Because enumerating through a collection is usually not thread-safe a yield return
is not either.
这篇关于C#线程安全的收益率返回值安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!