Runtime.Caching.MemoryCache 将许多项添加到缓存时抛出 OutOfMemoryException

Vah*_*ari 6 .net c# caching

对于一些繁重的计算,我想将临时结果放入 MemoryCache 并在需要时再次加载它。但是当我将 200 万个对象放入 Cache 时,它​​会抛出 OutOfMemoryException。

我在带有 8GB 内存的 Windows 7 64 位上运行程序。

当我查看任务管理器时,我发现我的应用程序只占用了 1.5 GB 内存,然后崩溃了。这段代码类似于我在我的程序中所做的

NameValueCollection config = new NameValueCollection
{
    {"cacheMemoryLimitMegabytes", "4000"},
    {"physicalMemoryLimitPercentage", "100"}
};
MemoryCache cache = new MemoryCache("MyCache", config);
CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration };
for (int i = 0; i < 4000000; i++)
{
    var resultOfTempOperation = DoOperation();
    CacheItem newEmployee = new CacheItem(Guid.NewGuid().ToString(), new SomeClass());
    cache.Add(newEmployee, policy);
}
Run Code Online (Sandbox Code Playgroud)

我的代码有什么问题?

Kic*_*aha 4

在视觉工作室中转到

解决方案>属性>配置属性>平台

如果您需要使用这么多内存,请确保您正在针对 x64 进行编译。(您已达到 32 位限制)