gpt4 book ai didi

c# - MemoryCache 不遵守配置中的内存限制

转载 作者:IT王子 更新时间:2023-10-29 03:38:13 27 4
gpt4 key购买 nike

我正在使用 .NET 4.0 MemoryCache应用程序中的类并试图限制最大缓存大小,但在我的测试中,缓存似乎并没有真正遵守限制。

我正在使用设置,according to MSDN ,应该限制缓存大小:

  1. CacheMemoryLimitMegabytes: The maximum memory size, in megabytes, that an instance of an object can grow to."
  2. PhysicalMemoryLimitPercentage: "The percentage of physical memory that the cache can use, expressed as an integer value from 1 to 100. The default is zero, which indicates that MemoryCache instances manage their own memory1 based on the amount of memory that is installed on the computer." 1. This is not entirely correct-- any value below 4 is ignored and replaced with 4.

我知道这些值是近似值而不是硬性限制,因为清除缓存的线程每 x 秒触发一次,并且还取决于轮询间隔和其他未记录的变量。然而,即使考虑到这些差异,当第一个项目在设置 CacheMemoryLimitMegabytesPhysicalMemoryLimitPercentage 后从缓存中逐出时,我看到缓存大小非常不一致测试应用程序。为了确保我对每个测试进行了 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

这是测试应用程序:

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

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

最佳答案

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

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

下面的代码反射(reflect)出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);
}

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

因此假设发生了 Gen2 GC,我们遇到了问题 2,即 ref2.ApproximateSize 在实际近似缓存大小方面做得很糟糕。通过 CLR 垃圾搜索,我发现这是一个 System.SizedReference,这就是它获取值的方式(IntPtr 是 MemoryCache 对象本身的句柄):

[SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern long GetApproximateSizeOfSizedRef(IntPtr h);

我假设 extern 声明意味着它此时进入非托管窗口领域,我不知道如何开始找出它在那里做什么。从我观察到的情况来看,它在尝试估算整体大小方面做得很糟糕。

第三个值得注意的事情是对 manager.UpdateCacheSize 的调用,听起来它应该做些什么。不幸的是,在这应该如何工作的任何正常示例中,s_memoryCacheManager 将始终为空。该字段是从公共(public)静态成员 ObjectCache.Host 设置的。这暴露给用户,如果他愿意的话,可以乱搞,我实际上能够通过将我自己的 IMemoryCacheManager 实现混合在一起,将其设置为 ObjectCache.Host,然后运行示例,使它像预期的那样工作.不过,到那时,您似乎还不如制作自己的缓存实现,甚至不必理会所有这些东西,尤其是因为我不知道是否将您自己的类设置为 ObjectCache.Host(静态的,所以它会影响每个人这些可能正在处理中)来测量缓存可能会弄乱其他东西。

我不得不相信至少有一部分(如果不是几部分的话)只是一个直接的错误。很高兴听到 MS 的某个人说这件事是怎么回事。

这个巨大答案的 TLDR 版本:假设此时 CacheMemoryLimitMegabytes 完全失效。您可以将其设置为 10 MB,然后继续将缓存填充到 ~2GB 并在不触发项目删除的情况下抛出内存不足异常。

关于c# - MemoryCache 不遵守配置中的内存限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6895956/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com