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) {