diff --git a/PerfectNumbers.Core/PrimeOrderCalculator.cs b/PerfectNumbers.Core/PrimeOrderCalculator.cs index 6493d6d..1f205cd 100644 --- a/PerfectNumbers.Core/PrimeOrderCalculator.cs +++ b/PerfectNumbers.Core/PrimeOrderCalculator.cs @@ -795,48 +795,37 @@ internal static partial class PrimeOrderCalculator private static bool TryGetCachedPrimality(ulong value, out bool isPrime) { - Dictionary? cache = Volatile.Read(ref _primalityCache); - if (cache is null) + _primalityCacheLock.EnterReadLock(); + try { - isPrime = default; - return false; - } + Dictionary? cache = _primalityCache; + if (cache is null) + { + isPrime = default; + return false; + } - return cache.TryGetValue(value, out isPrime); + return cache.TryGetValue(value, out isPrime); + } + finally + { + _primalityCacheLock.ExitReadLock(); + } } private static void CachePrimalityResult(ulong value, bool isPrime) { - Dictionary? cache = Volatile.Read(ref _primalityCache); - if (cache is not null && cache.TryGetValue(value, out bool existing) && existing == isPrime) - { - return; - } - _primalityCacheLock.EnterWriteLock(); try { - Dictionary? current = _primalityCache; - if (current is null) + Dictionary? cache = _primalityCache; + if (cache is null) { - Dictionary newCache = new() - { - [value] = isPrime, - }; - Volatile.Write(ref _primalityCache, newCache); - return; + cache = new Dictionary(); + _primalityCache = cache; } - if (current.TryGetValue(value, out bool existingValue) && existingValue == isPrime) - { - return; - } - - Dictionary updated = new(current) - { - [value] = isPrime, - }; - Volatile.Write(ref _primalityCache, updated); + cache[value] = isPrime; } finally {