Tim TrottTim TrottWhen nothing goes right, go left

Simple ASP.Net Caching in C#

By , Wednesday 3rd April 2013 in ASP.Net

A short ASP.NET caching snippet written in C# for ASP.Net or MVC which stores data in the cache reducing page generation times.

This ASP.Net caching technique is useful for scenarios where data is retrieved from a database or third party API and does not have to be updated in real time.

In the example below, there is a custom data type called MyDataType, although any .Net class can be used here.

Firstly, a call is made to get the object data from the cache location "key". If the data is not found the function returns null, so by checking if the result is null we know if the data was found in the cache or not. If the data is not found, we simply go ahead and get the data from the database or API as normal. The data is then inserted into the cache for next time.

The example below has two calls to HttpRuntime.Cache.Insert - you only need to use one of them. The two examples given are for storing the data indefinitely and for storing the data for a specified time.

If the data is found in the cache then it can be checked to make sure that it is the correct data type (nothing has overridden the data with something else for example) then it is cast back to the original data type.

MyDataType dataToGet = new MyDataType();
 
object cachedObjectData = HttpRuntime.Cache.Get("key");
if (cachedObjectData == null)
{
    // Data was not found in the cache so get the data from database or external API
    dataToGet = GetMyData();
 
    // Put the data into the cache (make sure the key is the same as above
    // Data will remain in the cache until the application is restarted or the cache cleared
    HttpRuntime.Cache.Insert("key", dataToGet);
 
    // If you want to force a refresh of the data periodically, use an expiration
    // This will cause the data to be invalid after one hour and will be got from source again.
    // You can use any of the TimeSpan methods to keep data for a few seconds to days or years.
    HttpRuntime.Cache.Insert("key", dataToGet, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromHours(1));
}
else
{
    // Data was found in the cache, now cast to original data type
    // You should do some checking that the cached data is the correct data type to prevent invalid cast exception
    dataToGet = (MyDataType)cachedObjectData;
}

My website and its content are free to use without the clutter of adverts, tracking cookies, marketing messages or anything else like that. If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

About the Author

Tim Trott

Tim is a professional software engineer, designer, photographer and astronomer from the United Kingdom. You can follow him on Twitter to get the latest updates.

Further Reading
Leave a Reply

Your email address will not be published.