diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentDictionary.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentDictionary.cs index aa79092e64064..fb49255cfe655 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentDictionary.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentDictionary.cs @@ -642,6 +642,12 @@ public void Clear() { AcquireAllLocks(ref locksAcquired); + // If the dictionary is already empty, then there's nothing to clear. + if (AreAllBucketsEmpty()) + { + return; + } + Tables tables = _tables; var newTables = new Tables(new Node[DefaultCapacity], tables._locks, new int[tables._countPerLock.Length]); _tables = newTables; @@ -1421,20 +1427,7 @@ public bool IsEmpty ReleaseLocks(0, acquiredLocks); } - bool AreAllBucketsEmpty() - { - int[] countPerLock = _tables._countPerLock; - - for (int i = 0; i < countPerLock.Length; i++) - { - if (countPerLock[i] != 0) - { - return false; - } - } - return true; - } } } @@ -1874,6 +1867,22 @@ void ICollection.CopyTo(Array array, int index) #endregion + + private bool AreAllBucketsEmpty() + { + int[] countPerLock = _tables._countPerLock; + + for (int i = 0; i < countPerLock.Length; i++) + { + if (countPerLock[i] != 0) + { + return false; + } + } + + return true; + } + /// /// Replaces the bucket table with a larger one. To prevent multiple threads from resizing the /// table as a result of races, the Tables instance that holds the table of buckets deemed too