Search code examples
c#asp.netcachingmemorycache

MemoryCache object become null


I have a Cache-manager class that caches an object, but I have a problem with it. Sometimes, totally random, MemoryCache.Default.Contains(keyName) becomes null, and my application works without any caching. I'm totally frustrated with this problem.

What should I do?

It's ASP.NET WebForms 4.0 running on Windows Server 2008 R2 with .NET 4.5 installed.

I never had this problem when I ran this application on the local machine.

public class CacheManager
{
    private static object _lockObject = new object();
    public static object GetItem(string keyName, Func<object> action)
    {
        if (!MemoryCache.Default.Contains(keyName)) {
            System.Threading.Monitor.Enter(_lockObject);
            try {
                if (!MemoryCache.Default.Contains(keyName)) {
                    dynamic value = action.Invoke();
                    MemoryCache.Default.Set(keyName, value, System.DateTime.Now.AddDays(10));
                }
            }
            finally {
                System.Threading.Monitor.Exit(_lockObject);
            }
        }

        return MemoryCache.Default.GetCacheItem(keyName).Value;
    }

    public static void ResetCache(string keyName)
    {
        if (MemoryCache.Default.Contains(keyName)) {
            System.Threading.Monitor.Enter(_lockObject);
            try {
                if (MemoryCache.Default.Contains(keyName)) {
                    MemoryCache.Default.Remove(keyName);
                }
            }
            finally {
                System.Threading.Monitor.Exit(_lockObject);
            }
        }
    }
}

Solution

  • Finally I found the problem. I checked IIS and my application pool was getting reset because of UnexpectedException. And there was nothing wrong with my code.