如果我理解正确,那么并发集合将创建快照作为Enumerator
循环中使用的foreach
的源,这需要锁定。
它们是否每次都缓存快照或锁定?这会对性能产生潜在影响吗?我对微测量表示怀疑,因为它们很容易导致错误的结论,并试图了解其内部运作方式。
谢谢!
答案 0 :(得分:1)
否,它似乎没有缓存。以下是ConcurrentBag<T>
中的代码:
public IEnumerator<T> GetEnumerator()
{
if (m_headList != null)
{
bool lockTaken = false;
try
{
FreezeBag(ref lockTaken);
return ToList().GetEnumerator();
}
finally
{
UnfreezeBag(lockTaken);
}
}
return new List<T>().GetEnumerator();
}
private List<T> ToList()
{
List<T> list = new List<T>();
for (ThreadLocalList threadLocalList = m_headList; threadLocalList != null; threadLocalList = threadLocalList.m_nextList)
{
for (Node node = threadLocalList.m_head; node != null; node = node.m_next)
{
list.Add(node.m_value);
}
}
return list;
}