Kentico CMS 6.0 Developer's Guide

Caching in custom code

Caching in custom code

Previous topic Next topic Mail us feedback on this topic!  

Caching in custom code

Previous topic Next topic JavaScript is required for the print function Mail us feedback on this topic!  

In the following code extract, you can see how a CachedSection object can be used to cache data in your custom code. It checks if the item is in the cache (it also handles if the item should be cached or not based on the given cache minutes and boolean result of a specified condition). If it is in the cache, it returns the item, if not, it reports that the data should be loaded, you handle the loading and put the result back to the object. Then, the object stores the data to the cache automatically.

 

using CMS.SiteProvider;

using CMS.GlobalHelper;

 

private void CachingExample()

{

  DataSet data = null;

 

  // Cache the data for 10 minutes with key "mykey"

  using (CachedSection<DataSet> cs = new CachedSection<DataSet>(ref data, 10, true, null, "mykey"))

   {

      if (cs.LoadData)

       {

           data = UserInfoProvider.GetAllUsers(); // Get data from database

           cs.CacheDependency = CacheHelper.GetCacheDependency("somekey"); // Cache dependency

           cs.Data = data; // Save data to cache

       }

   }

}