diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentStack.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentStack.cs index ef3c9ffcaad61d..78dc57b94a0492 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentStack.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentStack.cs @@ -586,6 +586,8 @@ private int TryPopCore(int count, out Node? poppedHead) Node? head; Node next; int backoff = 1; + int shift = Numerics.BitOperations.Log2(int.MaxValue / (uint)count); + int checkHeadMask = (1 << shift) - 1; while (true) { head = _head; @@ -605,6 +607,13 @@ private int TryPopCore(int count, out Node? poppedHead) for (; nodesCount < count && next._next != null; nodesCount++) { next = next._next; + if ((nodesCount & checkHeadMask) == 0) + { + if (head != _head) + { + break; + } + } } // Try to swap the new head. If we succeed, break out of the loop.