Skip to content

System.Runtime.Caching.MemoryCache does not evict on NET 3.1/5/6 #62516

Open
@indy-singh

Description

@indy-singh

Description

When running the sample code on NET Framework 4.7.2 or 4.8.0. You can see items being evicted from the cache as you'd expect.

However, when the same sample code on netcoreapp3.1, net5.0, or net6.0 it does not evict the cache.

Reproduction Steps

var cache = new MemoryCache("a", new NameValueCollection
{
	{ "cacheMemoryLimitMegabytes", "1" },
	{ "pollingInterval", "00:00:10"}
});

var sum = 0L;

var stopwatch = Stopwatch.StartNew();

while (true)
{
	if (stopwatch.Elapsed >= cache.PollingInterval)
	{
		Console.WriteLine(string.Join("\t", stopwatch.Elapsed.ToString("mm\\:ss"), "should begin to evict"));
	}

	var toBeCached = new string('a', 81920 * 10);

	sum += toBeCached.Length;

	if (sum >= cache.CacheMemoryLimit)
	{
		Console.WriteLine(string.Join("\t", stopwatch.Elapsed.ToString("mm\\:ss"), "over!"));
	}

	var key = Guid.NewGuid().ToString();

	var cacheItemPolicy = new CacheItemPolicy
	{
		AbsoluteExpiration = DateTimeOffset.Now.Add(TimeSpan.FromHours(1)),
		RemovedCallback = arguments => Console.WriteLine(string.Join("\t", stopwatch.Elapsed.ToString("mm\\:ss"), "remove: " + arguments.CacheItem.Key))
	};

	if (cache.Add(key, toBeCached, cacheItemPolicy))
	{
		Console.WriteLine(string.Join("\t", stopwatch.Elapsed.ToString("mm\\:ss"), "add: " + key));
	}

	Thread.Sleep(TimeSpan.FromSeconds(2));
}

Expected behavior

It should begin to evict as it does on .NET Framework 4.7.2/4.8.

Actual behavior

It does not evict on; netcoreapp3.1, net5.0, or net6.0

Regression?

Yes, it worked as expected on .NET Framework 4.7.2/4.8.

Known Workarounds

No known workarounds, except we ripped out MemoryCache. We are aware that the documentation does say we should use IMemoryCache, but that is not a 1:1 replacement for us.

Configuration

Which version of .NET is the code running on?

NET Framework 4.7.2 - works
NET Framework 4.8.0 - works
netcoreapp3.1 - broken
net5.0 - broken
net6.0 - broken

What OS and version, and what distro if applicable?

We tested on:-

OS Name:                   Microsoft Windows 10 Pro
OS Version:                10.0.19043 N/A Build 19043

And

OS Name:                   Microsoft Windows Server 2019 Standard
OS Version:                10.0.17763 N/A Build 17763

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions