Added condition of empty for concurrent dictionary (#44581)
authorShreyas Jejurkar <shreyasjejurkar123@live.com>
Tue, 17 Nov 2020 12:56:18 +0000 (18:26 +0530)
committerGitHub <noreply@github.com>
Tue, 17 Nov 2020 12:56:18 +0000 (07:56 -0500)
* Added condition of empty for concurrent dictionary

Collection is already empty why to initialize it again with new emtpy tables.

* Made AreAllBucketsEmpty method private from local function.

Addressed PR feedback.

* Addressed PR feedback.

Comment corrected.

Co-authored-by: Stephen Toub <stoub@microsoft.com>
Co-authored-by: Stephen Toub <stoub@microsoft.com>
src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentDictionary.cs

index aa79092..fb49255 100644 (file)
@@ -642,6 +642,12 @@ namespace System.Collections.Concurrent
             {
                 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 @@ namespace System.Collections.Concurrent
                     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 @@ namespace System.Collections.Concurrent
 
         #endregion
 
+
+        private bool AreAllBucketsEmpty()
+        {
+            int[] countPerLock = _tables._countPerLock;
+
+            for (int i = 0; i < countPerLock.Length; i++)
+            {
+                if (countPerLock[i] != 0)
+                {
+                    return false;
+                }
+            }
+
+            return true;
+        }
+
         /// <summary>
         /// 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