Web Parts and Caching

Web Part developers can use the Web Part cache to store property values and to expedite data retrieval. Values are stored in the Web Part cache on a per-part or per-user basis by specifying the storage type in the call to the PartCacheRead and PartCacheWrite methods.

You can determine the type of cache to use—either the SharePoint database or the ASP .NET Cache object—by the setting of the WebPartCache element in the web.config file. Possible settings follow:

  • None disables caching.
  • Database uses the SharePoint database.
  • CacheObject uses the ASP.NET Cache object (the default).

For example, to use the SharePoint database for caching, create the following web.config file entry:

       <WebPartCache Storage="Database"/>

Cache details

You use the PartCacheWrite and PartCacheRead methods of the WebPart class to manage caching, and the PartCacheInvalidate method to invalidate part or all of the Web Part cache (for example, if a property changes on the Web Part). To obtain information about the cache type at run-time, use the CacheType property.

A key is used to find cache entries, allowing an arbitrary number of name-value pairs to be stored.

Note Cached data may not be available on subsequent invocations of the Web Part, as the system can expunge values from the cache at any time.

Using the SharePoint database

During cache storage in in the database, the following occurs:

  • If parts are not personalized, Personal cache entries (a call to the PartCacheWrite method with storage set to Storage.personal) are not stored.
  • If parts are Personal (added to the page in personal view), the Shared and Personal cache entries are stored in the same place. If the PartCacheInvalidate method is called with a storage value of Shared or Personal, all the cache is cleared.

When using the database for storage, both the Shared and Personal cache are limited to 2 MB. If this limit is exceeded, no error is displayed, but the cache entry will be lost. Additionally, if the storage type is Personal, it is charged against the user's quota.

Any object placed in the database cache must be marked as serializable (System.SerializableAttribute).

Using the ASP.NET Cache object

ASP.NET also provides caching functionality that the Web Part can use through the Cache object.

Caches stored using ASP.NET are limited by the size allowed by the Cache object. For more information about the Cache class, see the System.Web.Caching namespace.

Note Static Web Parts can only use caching if WebPartCacheStorage is set to CacheObject. No exception is raised if the setting is Database, but no cache entry is stored. Changes to the .aspx file cause the Web Part cache to get purged for static Web Parts.

For more information about the WebPartStorage attribute, see Web Part Storage.