alastairtree / LazyCache

An easy to use thread safe in-memory caching service with a simple developer friendly API for c#
https://nuget.org/packages/LazyCache
MIT License
1.71k stars 159 forks source link

PostEvictionCallBack causing memory leak #191

Open kcritchnau-qt opened 11 months ago

kcritchnau-qt commented 11 months ago

Describe the bug I am using the RegisterPostEvictionCallback to auto-refresh my cache when it expires. This is causing my memory usage to gradually creep up over time. I am logging when the eviction happens, as well as when the GetOrAdd() is being called, and both are firing. I suspect it's an issue with garbage collection.

Here's a graph of the memory usage today. I had a failed deployment at 10:20 that took the site down for a while, as you can see once it came back up the memory usage has crept up consistently.

image

Here is the code I am using to configure the cache:

private MemoryCacheEntryOptions GetCacheEntryOptions()
      {
          var options = new LazyCacheEntryOptions().SetAbsoluteExpiration(_cacheOptions.Timeout,
              ExpirationMode.ImmediateEviction);

          options.RegisterPostEvictionCallback((keyEvicted, value, reason, state) =>
          {
              if (reason is not (EvictionReason.Expired or EvictionReason.TokenExpired)) return;
              var keyString = keyEvicted.ToString();
              _logger.LogInformation("Evicted division {KeyString} from cache", keyString);
              var division = int.Parse(keyString);
              _appCache.GetOrAdd(keyEvicted.ToString(), () => GetDivisionUsersForCache(division),
                  GetCacheEntryOptions());
          });
          return options;
      }

Expected behavior The memory usage stays consistent.

** Framework and Platform