Note that there are some explanatory texts on larger screens.

plurals
  1. POMemoryCache Empty : Returns null after being set
    text
    copied!<p>I have a problem with an MVC 3 application that is using the new .NET 4 System.Runtime.Caching MemoryCache. I notice that after a seemingly unpredictable time, it stops caching stuff, and acts like it's empty. Consider this bit of code that I took straight from a test View in ASP.NET MVC:</p> <pre><code>MemoryCache.Default.Set("myname","fred", new CacheItemPolicy() { SlidingExpiration = new TimeSpan(0,5,0) }); Response.Write(MemoryCache.Default["myname"]); </code></pre> <p>When it's working, predictably "fred" gets printed. However, when the problem starts to occur, despite the <code>Set()</code>, the value of <code>MemoryCache.Default["myname"]</code> is null. I can prove this by setting a breakpoint on the <code>Response.Write()</code> line and directly setting and reading from the cache using the Immediate Window - It just won't set it and stays null! The only way to get it working again then is to cause an AppDomain recycle.</p> <p>Intriguingly I can provoke the problem into occurring when the app is working normally by breaking on the <code>Response.Write()</code> line and running <code>MemoryCache.Default.Dispose()</code>. After that, MemoryCache.Default is not null itself (why is this?), but won't save anything set on it. It doesn't cause any errors, but just won't save anything. </p> <p>Can anybody verify this and explain? As I believe I have discovered, when the app stops working on its own, <em>something</em> is Disposing <code>MemoryCache.Default</code>, but it's not me!</p> <hr> <p><strong>UPDATE</strong></p> <p>Well, I'm sick of this prob now! CLRProfiler doesn't seem to work with MVC 3. SciTech's CLR tool was good - so was RedGate ANTS. But all they told me was that the MemoryCache object is being disposed by <em>something</em>! I also proved (via a timestamp print) that a PartialView on my page that should be cached (specified by OutputCacheAttribute) stops being cached after a few minutes - it starts refreshing with every call to the page. Just to clarify the environment, I am running directly on the IIS 7.5 server on my development workstation running Win 7 Ultimate. The memory tools mentioned above suggest I am only using about 9mb of memory in terms of objects in play.</p> <p>In desperation I have changed my caching code to first search for an ambient HttpContext to hook onto and use its Caching functionality, if one's available. Early tests show this is reliable, but it feels like a nasty hack.</p> <p>Am getting the feeling that MemoryCache and OutputCache aren't warranted to work with MVC 3...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload