andres descalzo
andres descalzo

Reputation: 14967

MemoryCache always returns "null" after first expiration

I have the following problem, I have this kind of cache management:

public class CacheManager : ICacheManager {

    private readonly ObjectCache cache;

    public CacheManager() {
        this.cache = MemoryCache.Default;
    }

    public void AddItem(string key, object itemToCache, double duration) {
        var end = DateTime.Now.AddSeconds(duration);
        this.cache.Add(key, itemToCache, end);
    }

    public T Get<T>(string key) where T : class {
        try {
            return (T)this.cache[key];
        }
        catch (Exception ex) {
            return null;
        }
    }

    public void Remove(string key) {
        this.cache.Remove(key);
    }
}

is quite simple.

Edit I (bug fixes in the text of the question)

Problem: When the cache for any key expires, all the following calls to get any object in cache return "null". I check the keys and are always correct.

The problem occurs only in the client's server in my PC and my server works perfectly.

thanks.

Edit II (advances)

When we restart the Application Pool in the customer's server, you problem is solved for a few hours.

There is a specific Application Pool for our site with the following settings:

Pipeline Manager mode: Integrated Framework: v4.0 Enable 32-bit Application: True.

Other settings such as default.

On the server we have 2 sites, one with "Enable 32-bit Application" enabled, if both are disabled the error occurred, but do not know if this is the problem.

Edit III (advances)

As we fail to solve the problem, we decided to switch to Httpcontext.Current.Cache, and we could solve the problem. We wanted another solution and continue to use MemoryCache but did not result.

Upvotes: 7

Views: 8570

Answers (2)

James McCormack
James McCormack

Reputation: 9944

Resurrecting an old question, but I believe this problem is due to a bug that was only fixed in ASP.NET 4.5, but has a hotfix for earlier versions.

See this thread: MemoryCache Empty : Returns null after being set

Upvotes: 2

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

Caching of this kind normally require your code to be in form "if an item is not in the cache then create the item, use the item that was created and also add to the cache, otherwise use the item from the cache". So normally it should be a problem if an item is not in the cache.

Common reason for items to disappear from the cache is high memory usage. In this case memory cache may immediately evict items as soon as they added to cache. This behavior is very common for applications running in 32 bit (x86), sepecially on servers handling a lot of requests or large amount of data.

To verify - collect memory conuters and process' bitness. Consider adding code to listen for removal of items from the cache by using MemoryCache.CreateCacheEntryChangeMonitor and corresponding events.

Upvotes: 2

Related Questions