C# – MemoryCache always returns “null” after first expiration

asp.net-mvcciismemorycache

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.

Best Answer

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