Simple ASP.Net Caching Data in C# to Improve Performance

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

By Tim Trott | C# ASP.Net MVC | April 3, 2013

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.

C#
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 the 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 the 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 the original data type
    / You should do some checking that the cached data is the correct data type to prevent an invalid cast exception
    dataToGet = (MyDataType)cachedObjectData;
}
Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

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.

There are no comments yet. Why not get the discussion started?

We respect your privacy, and will not make your email public. Learn how your comment data is processed.