MemoryCache does not obey memory limits in configuration

前端 未结 7 1091
暖寄归人
暖寄归人 2020-11-28 18:01

I’m working with the .NET 4.0 MemoryCache class in an application and trying to limit the maximum cache size, but in my tests it does not appear that the cache is actually o

相关标签:
7条回答
  • 2020-11-28 18:39

    I've encountered this issue as well. I'm caching objects that are being fired into my process dozens of times per second.

    I have found the following configuration and usage frees the items every 5 seconds most of the time.

    App.config:

    Take note of cacheMemoryLimitMegabytes. When this was set to zero, the purging routine would not fire in a reasonable time.

       <system.runtime.caching>
        <memoryCache>
          <namedCaches>
            <add name="Default" cacheMemoryLimitMegabytes="20" physicalMemoryLimitPercentage="0" pollingInterval="00:00:05" />
          </namedCaches>
        </memoryCache>
      </system.runtime.caching>  
    

    Adding to cache:

    MemoryCache.Default.Add(someKeyValue, objectToCache, new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddSeconds(5), RemovedCallback = cacheItemRemoved });
    

    Confirming the cache removal is working:

    void cacheItemRemoved(CacheEntryRemovedArguments arguments)
    {
        System.Diagnostics.Debug.WriteLine("Item removed from cache: {0} at {1}", arguments.CacheItem.Key, DateTime.Now.ToString());
    }
    
    0 讨论(0)
提交回复
热议问题