dotnetcore / EasyCaching

:boom: EasyCaching is an open source caching library that contains basic usages and some advanced usages of caching which can help us to handle caching more easier!
MIT License
1.97k stars 325 forks source link

InMemoryCaching: Difference between Set() and Add() #551

Open ricsiLT opened 2 months ago

ricsiLT commented 2 months ago

Description

Why is there a difference between these two methods? What are the uses for them? From testing I see that one of them increments the _cacheSize and the other one doesn't. Why is that?

Related code

        var maxSize = 50_000;
        var cacheOptions = new InMemoryCachingOptions
        {
            SizeLimit = maxSize,
            ExpirationScanFrequency = 1
        };
        var cache = new InMemoryCaching("default", cacheOptions);
        foreach (var i in Enumerable.Range(1, maxSize))
        {
            cache.Add(i.ToString(), i);
        }

        foreach (var i in Enumerable.Range(maxSize, 10))
        {
            cache.Set(i.ToString(), i);
        }

        cache.Set("50011", 11);
        await Task.Delay(6000); // Just in case expiration cleanup is in progress??

        Assert.NotNull(cache.Get("50011"));
        Assert.Null(cache.Get("1")); // I'd expect this key to be missing, but it's not??

Expected behavior: [What you expected to happen]

Regardless of .Add() or .Set(), SizeLimit should be honored.

Actual behavior: [What actually happened]

When using .Set(), size limit is honored. When using .Add(), size limit is ignored.

Specifications

    <PackageReference Include="EasyCaching.InMemory" Version="1.9.2" />