Vahid Jafari
Vahid Jafari

Reputation: 916

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

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?

Upvotes: 6

Views: 810

Answers (2)

Corith Malin
Corith Malin

Reputation: 1525

You've specified a memory limit but not when it should poll to trim the cache. You can do that by adding:

NameValueCollection config = new NameValueCollection
{
    {"cacheMemoryLimitMegabytes", "4000"},
    {"physicalMemoryLimitPercentage", "100"},
    {"pollingInterval", TimeSpan.FromMinutes(5).ToString()}
};

That will instruct the CLR to look for objects to evict every 5 minutes in you cache.

Upvotes: 0

Kickaha
Kickaha

Reputation: 3857

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)

Upvotes: 4

Related Questions