Cache Dependencies in SharePoint

While writing a data layer based on data stored in a SharePoint list, I implemented the collection as a static singleton that forced refreshes of the data every 15 minutes.

A colleague was doing something similar in a roll-up web part and we started discussing Cache Dependency objects used for the HttpContext. Could this work with SharePoint objects?

No, says "The Kid". But he gave me a good idea.

Therefore, I implemented the SPListItemCacheDependency and SPListCacheDependency objects.

To use the SPListItemCacheDependency:

   1: HttpContext.Current.Cache.Add("YourKey",


   2:     dataToCache,


   3:     new SPListItemCacheDependency(sourceItem),


   4:     Cache.NoAbsoluteExpiration,


   5:     Cache.NoSlidingExpiration,


   6:     CacheItemPriority.Normal,


   7:     null);




To use the SPListCacheDependency:





   1: HttpContext.Current.Cache.Add("YourKey",


   2:     dataToCache,


   3:     new SPListCacheDependency(sourceList),


   4:     Cache.NoAbsoluteExpiration,


   5:     Cache.NoSlidingExpiration,


   6:     CacheItemPriority.Normal,


   7:     null);




To monitor schema changes and property changes as well within the SPList and to decrease the change check poll from 10 seconds to 1 minute:





   1: HttpContext.Current.Cache.Add("YourKey",


   2:     dataToCache,


   3:     new SPListCacheDependency(sourceList, true, true, 60000),


   4:     Cache.NoAbsoluteExpiration,


   5:     Cache.NoSlidingExpiration,


   6:     CacheItemPriority.Normal,


   7:     null);




Download the code and documentation.

2 comments:

sarathy said...

Will the frequent creation of spsite and spweb objects to check for modifications be a problem?
Any thoughts on the same

Tobias Lekman said...

Well, that's why you can change the polling period as in the example above. You must obviously do some load testing/tracing to find out what the optimal balance would be for your application. There is always a balance between latest content and performance that needs to be fine tuned. In short - if you have enough traffic on your site to need something like this, then a check every 10 seconds will take very little processing compared to rendering the content from live data on each request.