title: MemoryCache object become null
body: <p>I have a Cache-manager class that caches an object, but I have a problem with it. Sometimes, totally random, <code>MemoryCache.Default.Contains(keyName)</code> becomes null, and my application works without any caching. I'm totally frustrated with this problem.</p>
  
  <p>What should I do?</p>
  
  <p>It's ASP.NET WebForms 4.0 running on Windows Server 2008 R2 with .NET 4.5 installed.</p>
  
  <p>I never had this problem when I ran this application on the local machine.</p>
  
  <pre><code>public class CacheManager
  {
      private static object _lockObject = new object();
      public static object GetItem(string keyName, Func&lt;object&gt; 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);
              }
          }
      }
  }
  </code></pre>