我正在使用应用程序中的.NET 4.0 MemoryCache类,并尝试限制最大缓存大小,但在我的测试中,似乎缓存实际上并未遵守限制。
根据MSDN,我正在使用这些设置来限制缓存大小:
我知道这些值是近似的,并不是硬限制,因为清除缓存的线程每隔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
这是测试应用程序:
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不遵守配置的内存限制?
发布于 2018-05-04 09:47:32
我想让你知道我编写了一个能MemoryCache
自动为你解决Gen 2收集问题的版本。
http://www.nuget.org/packages/SharpMemoryCache
你也可以在GitHub上找到它,如果你对我如何解决它感到好奇。代码有点简单。
https://stackoverflow.com/questions/-100008353
复制相似问题