title: When Does Asp.Net Remove Expired Cache Items?
body: <p>When you add an item to the <code>System.Web.Caching.Cache</code> with an absolute expiration date, as in the following example, how does Asp.Net behave? Does it:</p>
  
  <ol>
  <li><p>Simply mark the item as expired, then execute the <code>CacheItemRemovedCallback</code> on the   next access attempt?</p></li>
  <li><p>Remove the item from the cache and execute the <code>CacheItemRemovedCallback</code> immediately?</p>
  
  <pre><code>HttpRuntime.Cache.Insert(key,
                           new object(),
                           null, 
                           DateTime.Now.AddSeconds(seconds), 
                           Cache.NoSlidingExpiration,
                           CacheItemPriority.NotRemovable, 
                           OnCacheRemove);
  </code></pre></li>
  </ol>
  
  <p>MSDN appears to indicate that it happens immediately. For example, <a href="http://msdn.microsoft.com/en-us/library/ms178597(VS.80).aspx" rel="nofollow noreferrer">the "Expiration" section of the "ASP.NET Caching Overview"</a> says "ASP.NET automatically removes items from the cache when they expire." Similarly, the example from the topic <a href="http://msdn.microsoft.com/en-us/library/7kxdx246.aspx" rel="nofollow noreferrer">"How to: Notify an Application When an Item Is Removed from the Cache"</a> says "If more than 15 seconds elapses between calls to <code>GetReport</code> [a method in the example], ASP.NET removes the report from the cache."</p>
  
  <p>Still, neither of these is unambiguous. They don't say "the callback is executed immediately" and I could conceive of how their writers might have thought option 1 above counts as 'removing' an item. So I did a quick and dirty test, and lo, it appears to be executing immediately - I get regular sixty-second callbacks even when no one is accessing my site.</p>
  
  <p>Nonetheless, my test was quick and dirty, and in the comments to my answer to <a href="https://stackoverflow.com/questions/1395358/is-there-a-way-to-run-a-process-every-day-in-a-net-web-application-without-writi/1395447#1395447">Is there a way to run a process every day in a .Net web application without writing a windows service or SQL server jobs</a>, someone has suggested that Asp.Net actually defers removal and execution of the callback until something tries to access the cache again.</p>
  
  <p>Can anyone settle this authoritatively or is this just considered an implementation detail?</p>