46

I am adding caching to an ASP.NET web application. This is .NET 4, so I can use the classes in the System.Runtime.Caching namespace (which, as I understand it, was added to provide similar functionality to that found in System.Web.Caching, but for non-Web-apps.)

But since this is a web app, am I better off using System.Web.Caching? Or is the newer System.Runtime.Caching superior in some way?

2 Answers 2

47

Microsoft recommends using System.Runtime.Caching for all caching purposes. See this: http://msdn.microsoft.com/en-us/library/dd997357.aspx

Although, I have come across a couple threads where people are having issues with the MemoryCache.Default instance. After a while, it stops working properly. Any item you add using the Add or Set method does not actually get added to the cache. I tried the same and was able to reproduce this issue with explicitly calling MemoryCache.Default.Dispose() method.

Here are the links: MemoryCache Empty : Returns null after being set

http://forums.asp.net/t/1736572.aspx/1

My recommendation is to use the System.Web.Caching (HttpContext.Current.Cache)

UPDATE:

This issue has been fixed by MS. Check the accepted answer in the post below: Runtime Cache Issue Resolved

4
  • 4
    Big +1! Note though that Microsoft fixed the bug - see Scott Hanselman's answer to the linked question above.
    – TrueWill
    Commented Jun 27, 2013 at 17:03
  • 2
    Can you please update your answer? I found this question and your answer, but some more searching told me that there is now a fix for that so Runtime.Caching is recommended now :) Commented Nov 20, 2013 at 15:11
  • 1
    Updated the answer to reflect the latest status.
    – dotnetster
    Commented Nov 22, 2013 at 15:32
  • you should not call MemoryCache.Default.Dispose() method, if you plan use MemoryCache.Default afterwards. Instead do the following. var memoryCache = MemoryCache.Default; memoryCache.Trim(100); //for issues, when some cache items are not cleared foreach (var item in memoryCache.ToList()) { memoryCache.Remove(item.Key); } Commented Aug 16, 2016 at 19:33
12

System.Runtime.Caching allows you to cache across all .Net apps, not just the IIS worker process. So if you have a requirement that will access the cache in multiple scenarios, use System.Runtime. Also you can check this cache adapter which allows you to swap between runtime, web, and app fabric caching. https://bitbucket.org/glav/cacheadapter

One more thing, if you have a multi-server farm, with a load balanced configuration make sure you have sticky-sessions or a distributed cache model.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.