Object Caching - .NET 4

As a developer, we need to use all the tools at our disposal to develop faster and more robust applications. One of the ways we can achieve this is by using caching. Caching is the process of storing frequently used data on the server to fulfil subsequent requests. Now there are a few different types of caching available to the .NET developer, but in this article I am going to discuss data caching using the object cache. The cache object enables you to store everything from simple name / value pairs to more complex objects such as datasets and entire pages.

Previously, the cache object used to fall under the System.Web.Caching.Cache namespace. Due to it's power and awesomeness, many developers would copy this namespace into their projects and use it in other applications such as Windows Forms and WPF apps. With the release of .NET 4, the namespace has been refactored and totally rebuilt into the new namespace of System.Runtime.Caching. The old namespace is still available, but any new enhancements will be added to the System.Runtime.Caching namespace.

In this example, I am going to take a look at Object Caching. For more types of caching available to you in the .net framework - check out this link. Now, let's look at a code example and run through how easy it is to add some caching to your application. I'm going to use an example of some of the caching I use when building on this site.

To start, you add a reference to the System.Runtime.Caching object in your project.

Add Reference

If you wanted to add an item to the cache, you would need to do the following:

Add to Cache

In this line, we are obtaining a reference to the default MemoryCache instance. Using the new .NET Caching runtime, you can have multiple MemoryCaches inside a single application.

ObjectCache Cache = MemoryCache.Default;

Then we add the object to the cache along with a key. The key allows us to retrieve this at a later point.

Sometimes you might come across a scenario where a similar object will have similar name, in this case you might want to build a dynamic key string to identify your objects.

Cache.Add("Key", objectToCache, DateTime.Now.AddDays(30));

Retrieving our object is just as simple, but this time let's make a re-usable method that is a lot sexier.

For this example I have added the above method to a class called CacheLayer, and if we wanted to call the method that has just been created:

Cache Get

Let's put the whole thing together in a real world example and show the power of caching.

Cache Example

In the above example, we check if the cache contains the data that we are looking for based on the key. If it doesn't contain the data, we retrieve it from the Database and then add it to the cache. Then the next time that the method is called it won't have to hit the Database, but simply get the data from memory. This saves a lot of time and overhead!

NOTE: If you make changes on your application, you might not see them immediately because they might be in cache. You might need to remove the object in order to see your changes - you can always add them back in!

In order to wrap all this up, I have created a little class that you can easily call and use for your caching needs. If you would like to download just the class file - click here

Else if you prefer to download the full class library project with working unit tests



Tavis Basing - 10/7/2010
Well explained Dean, will definitely use this example in future projects. Cheers

kourosh - 10/11/2010
Hi, What about if you have two or more web servers? thanks

Stephen - 10/11/2010
kourosh - The only thing we found that does distributed caching was NCache - you can google it. It has worked quite well for us. I think the Microsoft product is App Fabric, which I haven't looked into yet...

Kris - 10/21/2010
Very good and useful article. I just have one question. How do I find out when an object placed in the cache (with a specific key) expire... or how much time is left to expire? Is it possible ?

sri - 3/29/2011
Good article.

Jeff M - 11/22/2011
Nice code, one comment...do not use the exists method, it could cause misleading results. when you call the method, it may exist, but a split second later it may not. You should instead just call the get, and if it returns null you know it does not exist.

Dave - 1/16/2012
You shouldn't use the try catch construct for flow control. Bad code smell.

Andreas - 2/21/2012
Please mention something about setting the expiration.

Brian - 3/19/2012
Per Dave's comment, I would update the Get logic to use Cache.Contains(key) instead of the try/catch block. Andreas, you could also add additional overloaded Add() methods to include a DateTime expiration to override the hard coded 30 day expiration.

Nelson Reis - 4/10/2012
This is a great article. Thanks for that. However, I'm having a problem. After 2 minutes, all items in the Cache are cleared and from that point on even if I add a new item to the cache, I won't be able to retrieve it, because the cache says it's always empty. What am I doing wrong?

sanjiv - 7/24/2012
Hi Nelson Reis, I am facing the same issue. the data in Cache is autometically cleaned up after 2 mints. Have you got the solution of this problem. Regards, Sanjiv K singh

Kelly - 11/30/2012
Thanks for this! Somehow I completely didn't notice this feature when .NET 4 was released.

Iain - 3/26/2013
Really useful - thanks for the post.

Juan - 7/19/2013
Thanks for this code... simple enough and a great jump start

kuhajeyan - 9/26/2013
Excellent post thank you.

Marlo - 11/3/2015
Thank you, still useful.

NetherX - 1/28/2017
Well, Thanks

Add your comment

300 Characters left

Please fill this in to confirm that you are human