Reputation: 6969
I did many tests, my MemoryCache instances get disposed after some time and always returns null when I call Get method. I think that is after PollingInterval.
To simulate you can start a new webapp and write this code:
private static MemoryCache mem = new MemoryCache("MyCache");
protected void Page_Load(object sender, EventArgs e)
{
string key = "MyKey";
mem.Set(key, "MyValue", new CacheItemPolicy() {AbsoluteExpiration = DateTimeOffset.Now.AddDays(1), Priority = CacheItemPriority.NotRemovable});
LtrValue.Text = mem.Get(key) as string;
}
I configured the PollingInterval to 30 hours an seems to work.
I thought could be the AppDomain Unload, but after some investigation I don´t think that is it:
1-) MSDN says to use MemoryCache for ASP.NET: http://msdn.microsoft.com/en-us/library/ff477235(v=vs.100).aspx And says that ASP.NET 4 cache is built with ObjectCache:
In ASP.NET 4, caching is implemented by using the ObjectCache class.
2-) AppDomain unload would reset statics variable, creating new MemoryCache instances.
3-) I attached a event to AppDomain Unload like the MemoryCache does(I saw the decompiled source) in my test it wasn´t called and memorycache get disposed.
References:
The same post at MSDN forum: http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/1233ffb3-6480-431b-94ca-1190f96cf5f6
http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/0a666d5e-9bda-47bd-8dd3-98d32eb5fe60
MemoryCache Empty : Returns null after being set
System.Runtime.Caching.MemoryCache strange behavior?
MemoryCache empty just after adding an object
MemoryCache does not obey memory limits in configuration
Upvotes: 2
Views: 2033
Reputation: 6969
Its really a bug, it was fixed in .NET 4.5 and they are working to back-port to .NET 4
http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/1233ffb3-6480-431b-94ca-1190f96cf5f6/
Upvotes: 1