【发布时间】:2014-07-21 02:00:11
【问题描述】:
我试图弄清楚应该如何使用 MemoryCache 以避免出现内存不足异常。我来自 ASP.Net 背景,缓存管理它自己的内存使用,所以我希望 MemoryCache 也会这样做。正如我制作的以下测试程序所示,情况似乎并非如此:
class Program
{
static void Main(string[] args)
{
var cache = new MemoryCache("Cache");
for (int i = 0; i < 100000; i++)
{
AddToCache(cache, i);
}
Console.ReadLine();
}
private static void AddToCache(MemoryCache cache, int i)
{
var key = "File:" + i;
var contents = System.IO.File.ReadAllBytes("File.txt");
var policy = new CacheItemPolicy
{
SlidingExpiration = TimeSpan.FromHours(12)
};
policy.ChangeMonitors.Add(
new HostFileChangeMonitor(
new[] { Path.GetFullPath("File.txt") }
.ToList()));
cache.Add(key, contents, policy);
Console.Clear();
Console.Write(i);
}
}
在大约达到 2GB 的内存使用量(任何 CPU)或消耗完我机器的所有物理内存 (x64)(16GB) 之后,上述内容会引发内存不足异常。
如果我删除 cache.Add 位,程序不会抛出异常。如果我在每次添加缓存后都包含对 cache.Trim(5) 的调用,我会看到它释放了一些内存,并且在任何给定时间(来自 cache.GetCount())在缓存中保留了大约 150 个对象。
是调用 cache.Trim 我的程序的责任吗?如果是这样,什么时候应该调用它(比如我的程序如何知道内存已满)?您如何计算百分比参数?
注意:我计划在长期运行的 Windows 服务中使用 MemoryCache,因此对其进行适当的内存管理至关重要。
【问题讨论】:
-
你找到一个好的答案了吗?
标签: c# .net caching memory-management windows-services