Blick auf source code:
public ICollection<TKey> Keys
{
get { return GetKeys(); }
}
private ReadOnlyCollection<TKey> GetKeys()
{
int locksAcquired = 0;
try
{
AcquireAllLocks(ref locksAcquired);
int count = GetCountInternal();
if (count < 0) throw new OutOfMemoryException();
List<TKey> keys = new List<TKey>(count);
for (int i = 0; i < _tables._buckets.Length; i++)
{
Node current = _tables._buckets[i];
while (current != null)
{
keys.Add(current._key);
current = current._next;
}
}
return new ReadOnlyCollection<TKey>(keys);
}
finally
{
ReleaseLocks(0, locksAcquired);
}
}
Er sperrt Sammlung und Rückgabe Kopieren von Schlüsseln
Es erstellt eine Kopie zurück. Siehe [hier] (https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/collections/Concurrent/ConcurrentDictionary.cs#L1931-L1955). – john
Es gibt einen 'Schnappschuss' (also ja, es wird gut funktionieren). Ich würde vorschlagen, 'var keys = dict.Select (z => z.Key) zu verwenden. Wo (k => k.Name ==" Example ");' um die Notwendigkeit von Snapshots (dh Sperren) zu reduzieren - dh es wird im Allgemeinen schneller sein. Oder einfach "foreach" über das Wörterbuch wie im Duplikat. – mjwills