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:
MemoryCache.Default.Set("myname","fred", new CacheItemPolicy() { SlidingExpiration = new TimeSpan(0,5,0) });
Response.Write(MemoryCache.Default["myname"]);
When it's working, predictably "fred" gets printed. However, when the problem starts to occur, despite the Set()
, the value of MemoryCache.Default["myname"]
is null. I can prove this by setting a breakpoint on the Response.Write()
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.
Intriguingly I can provoke the problem into occurring when the app is working normally by breaking on the Response.Write()
line and running MemoryCache.Default.Dispose()
. 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.
Can anybody verify this and explain? As I believe I have discovered, when the app stops working on its own, something is Disposing MemoryCache.Default
, but it's not me!
UPDATE
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 something! 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.
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.
Am getting the feeling that MemoryCache and OutputCache aren't warranted to work with MVC 3...
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…