Germstorm
Germstorm

Reputation: 9849

ASP.Net Cache sharing

I have an ASP.Net 4.0 web application which very frequently loads data from the database and does heavy calculations on it. I want to cache this loaded and prepared data in a central cache that can be accessed by every user and computer who uses the application.

Simple use-case:

I know that ASP.Net has a built-in cache mechanism. What I don't know is whether it can be shared between different users accessing the site on different computer at the same time. I would also like to know how the system behaves in a web farm environment.

Upvotes: 5

Views: 6490

Answers (3)

eduncan911
eduncan911

Reputation: 17634

While others have mentioned the built in ASP.NET Cache (System.Web.Caching), please note that .NET 4.0 introduces a whole new caching framework designed to work outside of the System.Web.Caching namespace:

System.Runtime.Caching

http://msdn.microsoft.com/en-us/library/system.runtime.caching(VS.100).aspx

Now, this is much more of a beast than the simple System.Web.Caching's Cache item. But, you get the advantage of having multiple cache stores, locking of cache objects/keys, and the extensibility points of creating your own external cache providers - such as one for Microsoft's new Velocity distributed caching system. It comes with a MemoryCache provider built-in.

It's really not that difficult to use. Straight from MSDN's article on the built-in MemoryCache provider (again, you can implement your own) using it in a WinForms application (you'd change the code for your web app):

http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.aspx

ObjectCache cache = MemoryCache.Default;
string fileContents = cache["filecontents"] as string;

if (fileContents == null)
{
    CacheItemPolicy policy = new CacheItemPolicy();

    List<string> filePaths = new List<string>();
    filePaths.Add("c:\\cache\\example.txt");

    policy.ChangeMonitors.Add(new 
    HostFileChangeMonitor(filePaths));

    // Fetch the file contents.
    fileContents = 
        File.ReadAllText("c:\\cache\\example.txt");

    cache.Set("filecontents", fileContents, policy);
}

Label1.Text = fileContents;

I've implemented NCache (mentioned above), as well as Memcached. I can tell you that Microsoft's Velocity is really the way to go for partitioning the data and setting up redundancy within the cache partitions itself (very cool). Not to mention, it's free!

Upvotes: 9

M4N
M4N

Reputation: 96626

As Eric wrote, you can use ASP.NET's built-in cache for what you what - it is shared between all sessions of your web app.

If you really want to (or need to) have a common cache for multiple machines (web farm), then you'd need some distributed caching solution, e.g. AppFabric, NCache or similar.

Upvotes: 3

Eric Petroelje
Eric Petroelje

Reputation: 60569

Yes, the built in ASP.NET cache is shared between all users (thread) in the application.

Upvotes: 2

Related Questions