MemoryCache在配置中不遵守内存限制

Can*_*rse 84 .net c# caching memorycache

我正在使用应用程序中的.NET 4.0 MemoryCache类并尝试限制最大缓存大小,但在我的测试中,似乎缓存实际上并未遵守限制.

我使用的设置,根据MSDN,应该限制缓存大小:

  1. CacheMemoryLimitMegabytes:对象实例可以增长到的最大内存大小(以兆字节为单位)."
  2. PhysicalMemoryLimitPercentage: "缓存可以使用的物理内存百分比,表示为1到100之间的整数值.默认值为零,表示 MemoryCache实例根据安装在内存中的内存量管理自己的内存 1电脑." 1.这不完全正确 - 忽略任何低于4的值并替换为4.

我理解这些值是近似值而不是硬限制,因为清除缓存的线程每隔x秒触发一次,并且还取决于轮询间隔和其他未记录的变量.然而,即使考虑到这些差异,在将测试应用程序中的CacheMemoryLimitMegabytes 和PhysicalMemoryLimitPercentage一起或单独设置后,当第一项从缓存中逐出时,我看到了非常不一致的缓存大小.为了确保我每次测试10次并计算出平均值.

这些是在具有3GB RAM的32位Windows 7 PC上测试以下示例代码的结果.在每次测试第一次调用CacheItemRemoved()之后获取缓存的大小.(我知道缓存的实际大小将大于此)

MemLimitMB    MemLimitPct     AVG Cache MB on first expiry    
   1            NA              84
   2            NA              84
   3            NA              84
   6            NA              84
  NA             1              84
  NA             4              84
  NA            10              84
  10            20              81
  10            30              81
  10            39              82
  10            40              79
  10            49              146
  10            50              152
  10            60              212
  10            70              332
  10            80              429
  10           100              535
 100            39              81
 500            39              79
 900            39              83
1900            39              84
 900            41              81
 900            46              84

 900            49              1.8 GB approx. in task manager no mem errros
 200            49              156
 100            49              153
2000            60              214
   5            60              78
   6            60              76
   7           100              82
  10           100              541
Run Code Online (Sandbox Code Playgroud)

这是测试应用程序:

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
namespace FinalCacheTest
{       
    internal class Cache
    {
        private Object Statlock = new object();
        private int ItemCount;
        private long size;
        private MemoryCache MemCache;
        private CacheItemPolicy CIPOL = new CacheItemPolicy();

        public Cache(long CacheSize)
        {
            CIPOL.RemovedCallback = new CacheEntryRemovedCallback(CacheItemRemoved);
            NameValueCollection CacheSettings = new NameValueCollection(3);
            CacheSettings.Add("CacheMemoryLimitMegabytes", Convert.ToString(CacheSize)); 
            CacheSettings.Add("physicalMemoryLimitPercentage", Convert.ToString(49));  //set % here
            CacheSettings.Add("pollingInterval", Convert.ToString("00:00:10"));
            MemCache = new MemoryCache("TestCache", CacheSettings);
        }

        public void AddItem(string Name, string Value)
        {
            CacheItem CI = new CacheItem(Name, Value);
            MemCache.Add(CI, CIPOL);

            lock (Statlock)
            {
                ItemCount++;
                size = size + (Name.Length + Value.Length * 2);
            }

        }

        public void CacheItemRemoved(CacheEntryRemovedArguments Args)
        {
            Console.WriteLine("Cache contains {0} items. Size is {1} bytes", ItemCount, size);

            lock (Statlock)
            {
                ItemCount--;
                size = size - 108;
            }

            Console.ReadKey();
        }
    }
}

namespace FinalCacheTest
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            int MaxAdds = 5000000;
            Cache MyCache = new Cache(1); // set CacheMemoryLimitMegabytes

            for (int i = 0; i < MaxAdds; i++)
            {
                MyCache.AddItem(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
            }

            Console.WriteLine("Finished Adding Items to Cache");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么MemoryCache不遵守配置的内存限制?

Dav*_*Hay 97

哇,所以我花了太多时间在CLR上用反射器挖掘,但我想我终于可以很好地处理这里发生的事情了.

正在正确读取设置,但在CLR本身中似乎存在一个根深蒂固的问题,看起来它会使内存限制设置基本上无用.

以下代码反映在System.Runtime.Caching DLL中,用于CacheMemoryMonitor类(有一个类似的类监视物理内存并处理其他设置,但这是更重要的一个):

protected override int GetCurrentPressure()
{
  int num = GC.CollectionCount(2);
  SRef ref2 = this._sizedRef;
  if ((num != this._gen2Count) && (ref2 != null))
  {
    this._gen2Count = num;
    this._idx ^= 1;
    this._cacheSizeSampleTimes[this._idx] = DateTime.UtcNow;
    this._cacheSizeSamples[this._idx] = ref2.ApproximateSize;
    IMemoryCacheManager manager = s_memoryCacheManager;
    if (manager != null)
    {
      manager.UpdateCacheSize(this._cacheSizeSamples[this._idx], this._memoryCache);
    }
  }
  if (this._memoryLimit <= 0L)
  {
    return 0;
  }
  long num2 = this._cacheSizeSamples[this._idx];
  if (num2 > this._memoryLimit)
  {
    num2 = this._memoryLimit;
  }
  return (int) ((num2 * 100L) / this._memoryLimit);
}
Run Code Online (Sandbox Code Playgroud)

您可能会注意到的第一件事是,它甚至不会在Gen2垃圾收集之后查看缓存的大小,而只是回退到cacheSizeSamples中现有的存储大小值.因此,你永远无法直接击中目标,但如果其余的工作,我们至少会在遇到真正麻烦之前进行尺寸测量.

因此,假设发生了Gen2 GC,我们遇到问题2,这就是ref2.ApproximateSize实际上接近缓存大小的可怕工作.通过CLR垃圾进行Slogging我发现这是一个System.SizedReference,这就是它为获取值而做的事情(IntPtr是MemoryCache对象本身的句柄):

[SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern long GetApproximateSizeOfSizedRef(IntPtr h);
Run Code Online (Sandbox Code Playgroud)

我假设extern声明意味着它在这一点上潜入非托管窗口,我不知道如何开始发现它在那里做了什么.从我观察到的情况来看,尽管它试图估算整体事物的大小是一件糟糕的工作.

第三个值得注意的事情是调用manager.UpdateCacheSize听起来应该做点什么.不幸的是,在这应该如何工作的任何正常样本中,s_memoryCacheManager将始终为null.该字段是从公共静态成员ObjectCache.Host设置的.如果用户选择的话,这可能会让用户感到困惑,而且我实际上可以通过将我自己的IMemoryCacheManager实现,将其设置为ObjectCache.Host,然后运行示例来实现这样的工作. .但是,在这一点上,似乎你可能只是制作自己的缓存实现,甚至没有烦恼所有这些东西,特别是因为我不知道是否将自己的类设置为ObjectCache.Host(静态,所以它影响每一个这些可能在那里的过程中测量缓存可能会弄乱其他东西.

我必须相信至少部分(如果不是几个部分)只是一个直接的错误.很高兴听到MS的某个人与这件事有什么关系.

这个巨大答案的TLDR版本:假设此时CacheMemoryLimitMegabytes完全被破坏.您可以将其设置为10 MB,然后继续将缓存填充到~2GB并吹掉内存不足异常,而不删除项目.

  • 我知道我刚刚在问题中提到过它,但为了完整起见,我会在这里再次提到它.我在Connect上打开了一个问题.http://connect.microsoft.com/VisualStudio/feedback/details/806334/system-runtime-caching-memorycache-do-not-respect-memory-limits (7认同)
  • 一个很好的答案谢谢你.我放弃了试图弄清楚这是怎么回事,现在通过计算输入/输出项目并根据需要手动调用.Trim()来管理缓存大小.我认为System.Runtime.Caching是我的应用程序的一个简单选择,因为它似乎被广泛使用,因此我认为不会有任何重大错误. (4认同)
  • 哇.这就是我爱的原因.我遇到了完全相同的行为,编写了一个测试应用程序并设法使我的PC多次崩溃,即使轮询时间低至10秒且缓存内存限制为1MB.感谢您的所有见解. (3认同)

Han*_*ney 29

我知道这个答案很晚才很疯狂,但迟到总比没有好.我想让你知道我写了一个版本,MemoryCache它会自动为你解决Gen 2 Collection问题.因此,只要轮询间隔指示内存压力,它就会进行修剪.如果您遇到此问题,请试试吧!

http://www.nuget.org/packages/SharpMemoryCache

如果你对我如何解决它很好奇,你也可以在GitHub上找到它.代码有点简单.

https://github.com/haneytron/sharpmemorycache

  • .NET中的@KarlCassar字符串大小相对于字节大小为"2n + 20",其中`n`是字符串的长度.这主要是由于Unicode支持. (5认同)
  • 这可以按预期工作,使用生成器测试,该生成器使用1000个字符的字符串填充缓存.尽管如此,将100MB的内容加到缓存中实际上会为缓存增加200-300MB,我觉得这很奇怪.也许有些过头而且我不算数. (2认同)

Aar*_*don 5

我也遇到过这个问题。我正在缓存每秒数十次被触发到我的进程中的对象。

我发现以下配置和用法大部分时间每 5 秒释放一次项目。

应用程序配置:

记下cacheMemoryLimitMegabytes。当它设置为零时,清除程序不会在合理的时间内启动。

   <system.runtime.caching>
    <memoryCache>
      <namedCaches>
        <add name="Default" cacheMemoryLimitMegabytes="20" physicalMemoryLimitPercentage="0" pollingInterval="00:00:05" />
      </namedCaches>
    </memoryCache>
  </system.runtime.caching>  
Run Code Online (Sandbox Code Playgroud)

添加到缓存:

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

确认缓存删除工作正常:

void cacheItemRemoved(CacheEntryRemovedArguments arguments)
{
    System.Diagnostics.Debug.WriteLine("Item removed from cache: {0} at {1}", arguments.CacheItem.Key, DateTime.Now.ToString());
}
Run Code Online (Sandbox Code Playgroud)