From 035672e7eaa6475e8f37f010e9408bfe045a6c9b Mon Sep 17 00:00:00 2001 From: mapogolions Date: Sun, 26 Sep 2021 02:52:13 +0500 Subject: [PATCH] Prevent cache from being resized --- .../src/MemoryCache.cs | 32 ++++++++----------- 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs b/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs index c14e9f68f11086..c4c7f2562857b5 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs +++ b/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs @@ -137,9 +137,19 @@ internal void SetEntry(CacheEntry entry) priorEntry.SetExpired(EvictionReason.Replaced); } - bool exceedsCapacity = UpdateCacheSizeExceedsCapacity(entry); + if (entry.CheckExpired(utcNow)) + { + entry.InvokeEvictionCallbacks(); + if (priorEntry != null) + { + RemoveEntry(priorEntry); + } + StartScanForExpiredItemsIfNeeded(utcNow); + return; + } - if (!entry.CheckExpired(utcNow) && !exceedsCapacity) + bool exceedsCapacity = UpdateCacheSizeExceedsCapacity(entry); + if (!exceedsCapacity) { bool entryAdded = false; @@ -192,22 +202,8 @@ internal void SetEntry(CacheEntry entry) } else { - if (exceedsCapacity) - { - // The entry was not added due to overcapacity - entry.SetExpired(EvictionReason.Capacity); - - TriggerOvercapacityCompaction(); - } - else - { - if (_options.SizeLimit.HasValue) - { - // Entry could not be added due to being expired, reset cache size - Interlocked.Add(ref _cacheSize, -entry.Size.Value); - } - } - + entry.SetExpired(EvictionReason.Capacity); + TriggerOvercapacityCompaction(); entry.InvokeEvictionCallbacks(); if (priorEntry != null) {