作者:自由战狼2012 | 来源:互联网 | 2023-02-04 10:32
MSDN声明从字典返回的枚举器不代表字典的时刻快照.虽然在多线程环境中很少需要它,但如果有人想要,获取ConcurrentDictionary的即时快照的最佳方法是什么?
1> apocalypse..:
只需调用ToArray()
方法.
这是一个源代码:
///
/// Copies the key and value pairs stored in the to a
/// new array.
///
/// A new array containing a snapshot of key and value pairs copied from the .
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "ConcurrencyCop just doesn't know about these locks")]
public KeyValuePair[] ToArray()
{
int locksAcquired = 0;
try
{
AcquireAllLocks(ref locksAcquired);
int count = 0;
checked
{
for (int i = 0; i [] array = new KeyValuePair[count];
CopyToPairs(array, 0);
return array;
}
finally
{
ReleaseLocks(0, locksAcquired);
}
}