Skip to content

2nd call to MemoryCache.Set() with the same key erases entry if cache is full #36039

Description

@anderslyman

Describe the bug

If I make a call to MemoryCache.Set() to update an existing item when the cache is full (size limit reached), the item is instead removed.

To Reproduce

Steps to reproduce the behavior:
LINQPad script: http://share.linqpad.net/kmpxj3.linq

void Main()
{
    var memoryCache = new MemoryCache(new MemoryCacheOptions
    {
        SizeLimit = 1 // <-- Setting to 2 fixes the issue
    });

    Set(memoryCache);
    memoryCache.Get("A").Dump(); // Yields 1
    Set(memoryCache);
    memoryCache.Get("A").Dump(); // Yields null
}

private void Set(MemoryCache memoryCache)
{
    //memoryCache.Remove("A"); // <-- Also fixes the issue

    memoryCache.Set("A", 1, new MemoryCacheEntryOptions
    {
        AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(1), 
        SlidingExpiration = TimeSpan.FromDays(1), 
        Size = 1
    });
}

Expected behavior

I would expect the item to be updated.

Additional Info

Initially posted a question here:
https://stackoverflow.com/questions/60626316/2nd-call-to-memorycache-set-with-the-same-key-erases-entry-if-cache-is-full

There was a link added by another user to a related, closed bug: dotnet/extensions#1889
While this is a different scenario, it seems like it might have the same root cause.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-Extensions-Cachingbughelp wanted[up-for-grabs] Good issue for external contributorsin-prThere is an active PR which will close this issue when it is merged

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions