Website development and design blog, tutorials and inspiration

Simple ASP.Net Caching in C#

Improve the performance of ASP.Net pages with caching

Written By on in C# 0

Simple ASP.Net Caching in C#

382 words, estimated reading time 2 minutes.

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.

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

Last updated on: Tuesday 20th June 2017

Did you Like this Post? Why not Like us on Facebook?


Further Reading

There are no comments for this post. Be the first!

Leave a Reply

Your email address will not be published.