Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime.Caching.MemoryCache throws OutOfMemoryException when add many item to cache

Tags:

c#

.net

caching

For some heavy calculation I want to to put temp results to MemoryCache and load it again when required. But when I put 2 million object to Cache, it throws OutOfMemoryException.

I run program on windows 7 64 bit with 8GB ram.

When I look to task manager I see that my application take only 1.5 GB ram and then crash. This code is similar to what I do in my program

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

What is wrong in my code?

like image 269
Vahid Jafari Avatar asked Sep 30 '15 11:09

Vahid Jafari


1 Answers

In visual studio go to

Solution>Properties>Configuration Properties>Platform

Make sure you are compiling for x64 if you need to use so much memory. (You are hitting the 32bit limit)

like image 121
Kickaha Avatar answered Nov 17 '22 11:11

Kickaha