MemoryCache does not obey memory limits in configuration

前端 未结 7 1123
暖寄归人
暖寄归人 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.

       
        
          
            
          
        
        
    

    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());
    }
    

提交回复
热议问题