title: .Net 4.0 MemoryCache Clearing
body: <p>I am using a .Net 4.0 MemoryCache in my WCF service.
  I originally was using the Default Cache as below:</p>
  
  <pre><code>var cache = MemoryCache.Default;
  </code></pre>
  
  <p>Then doing the usual pattern as trying to find something in the Cache, getting, then 
  setting into the cache if did not find (code snippet / pseudo code  as below):</p>
  
  <pre><code>var geoCoordinate = cache.Get(cacheKey) as GeoCoordinate;
  if (geoCoordinate == null)
  {
      geoCoordinate = get it from somewhere;
      cache.Set(cacheKey, geoCoordinate, DateTimeOffset.Now.AddDays(7));
  }
  </code></pre>
  
  <p>I was finding that my entries were disappearing after approx. 2 minutes. Even if my code placed the missing entries back into the cache, subsequent cache Gets would return null.
  My WCF Service is being hosted by IIS 7.5. If I recycled the App Pool, everything would work normally for 2 minutes, but then the pattern as described above would repeat.</p>
  
  <p>After doing some researching I then did the below to replace: 
      var cache = MemoryCache.Default;</p>
  
  <p>// WITH NEW CODE TO CREATE CACHE AS BELOW:</p>
  
  <pre><code> var config = new NameValueCollection();
   //Hack:  Set Polling interval to 10 days, so will no clear cache.
   config.Add("pollingInterval", "10:00:00:00");
   config.Add("physicalMemoryLimitPercentage", "90");
   config.Add("cacheMemoryLimitMegabytes", "2000");
  
   //instantiate cache
   var cache = new MemoryCache("GeneralCache", config);
  </code></pre>
  
  <p>It seems that no matter what I place into <code>physicalMemoryLimitPercentage</code>, or <code>cacheMemoryLimitMegabytes</code> does not seem to help. But placing the <code>pollingInterval</code> to a large <code>datespan</code> does. </p>
  
  <p>ie: If I set as below:
      config.Add("pollingInterval", "00:00:15:00");
  Then everything works fine for 15 minutes.</p>
  
  <p>Note: If my WCF service is hosted by IISExpress on my dev environment, I cannot reproduce.
  This also seems to happen when my WCF service is hosted by IIS 7.5.
  My app pool on IIS 7.5 is NOT recycling.</p>
  
  <p>Has anybody experienced something like this?
  I have seen the below:
  <a href="https://stackoverflow.com/questions/6895956/memorycache-strangeness">MemoryCache does not obey memory limits in configuration</a></p>
  
  <p>Thanks,</p>
  
  <p>Matt</p>