Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,29 @@ internal void SetEntry(CacheEntry entry)

priorEntry?.InvokeEvictionCallbacks();
}
else if (_options.HasSizeLimit && priorEntry != null && priorEntry.Size >= entry.Size)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to avoid a separate case here by passing priorEntry to UpdateCacheSizeExceedsCapacity? @Tratcher mentioned in the issue that he thought the cause here was that that method didn't consider the size of the evicted item.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree, for this case we should run the same logic we run for not exceeding capacity.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

{
bool entryAdded = coherentState._entries.TryUpdate(entry.Key, entry, priorEntry);

if (entryAdded)
{
long newSizeIncrement = entry.Size - priorEntry.Size;

if (newSizeIncrement < 0)
{
Interlocked.Add(ref coherentState._cacheSize, newSizeIncrement);
}

entry.AttachTokens();
}
else
{
entry.SetExpired(EvictionReason.Replaced);
entry.InvokeEvictionCallbacks();
}

priorEntry.InvokeEvictionCallbacks();
}
else
{
entry.SetExpired(EvictionReason.Capacity);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,31 @@ public void AddingReplacementExceedsCapacityRemovesOldEntry()
AssertCacheSize(0, cache); // addition was rejected due to size, and previous item with the same key removed
}

[Theory]
[InlineData(6)]
[InlineData(5)]
[InlineData(2)]
public void ReplaceOldEntryWithSameSizeOrLessNewEntryAtSizeLimitCapacity(int newValueSize)
{
var cache = new MemoryCache(new MemoryCacheOptions
{
SizeLimit = 6
});

AssertCacheSize(0, cache);

cache.Set("key", "oldValue", new MemoryCacheEntryOptions { Size = 6 });

Assert.Equal("oldValue", cache.Get("key"));

AssertCacheSize(6, cache);

cache.Set("key", "newValue", new MemoryCacheEntryOptions { Size = newValueSize });

Assert.Equal("newValue", cache.Get("key"));
AssertCacheSize(newValueSize, cache);
}

[Fact]
public void RemovingEntryDecreasesCacheSize()
{
Expand Down