Partager via


Implementing Caching in Your Application

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

The latest Enterprise Library information can be found at the Enterprise Library site.

patterns & practices Developer Center

On this page:
Configuring the Caching Application Block - Adding an In-Memory Cache Using Configuration, Adding an Isolated Storage Cache Using Configuration | Using the Object Cache - Retrieve the Cache from the Container, Adding Items to the Cache, Testing If an Item Is in the Cache, Using the Removed Callback, Using the Updated Callback

In this chapter, we'll discuss how you can apply the Silverlight Caching Application Block to your application to cache values. First, you will need to configure which cache you would like to use. Then you can retrieve the object cache from the container and start to interact with it.

Configuring the Caching Application Block

Now let us look at how you can add either the in-memory cache or the isolated storage cache to your application through XAML configuration. If you want, you can use both caches at the same time, as long as they each have a unique name.

Adding an In-Memory Cache Using Configuration

To add the in-memory cache to your application using a configuration file, you can follow these steps:

  1. Start the Enterprise Library configuration console

  2. Add the Caching Application Block for Silverlight:

    Hh852722.7011F3F22F80CE1E66ED8C5C42F8F9B1(en-us,PandP.51).png

  3. The In-Memory Cache is added by default. Configure the In-Memory Cache to fit your scenario. The name that you specify here is also the name that you should use when you wish to retrieve this cache from the container.

    Hh852722.5C83F1F4045D3C242B0DA325D75A8713(en-us,PandP.51).png

  4. Select Wizards -> Export to XAML. Browse to your Silverlight project and save it under the name Configuration.xaml.

    Follow link to expand image

  5. Add the configuration.xaml file to your Silverlight project and set the build action to Content in the file properties.

Adding an Isolated Storage Cache Using Configuration

  1. Start the Enterprise Library configuration console

  2. Add the Caching Application Block for Silverlight:

    Hh852722.7011F3F22F80CE1E66ED8C5C42F8F9B1(en-us,PandP.51).png

  3. Remove the In-Memory Cache, which is added by default, by right clicking the In-Memory Cache and selecting Delete In-Memory Cache.

    Hh852722.114CA88E3580531A0C062E31FCC5097F(en-us,PandP.51).png

  4. Add the Isolated Storage Cache by clicking the plus (+) sign and selecting the Isolated Storage Cache:

    Follow link to expand image

  5. Configure the Isolated Storage Cache to fit your scenario. The name of the Isolated Storage Cache is used for retrieving the correct cache implementation from the container.

    Follow link to expand image

  6. Select Wizards -> Export to XAML. Browse to your Silverlight project and save it under the name Configuration.xaml.

    Follow link to expand image

  7. Add the Configuration.xaml file to your Silverlight project and set the build action to Content in the file properties.

Using the Object Cache

Once you have configured either the in-memory cache or the isolated storage cache, you can use it from the container. It's recommended that you use the cache through the ObjectCache abstract base class, because this allows you to change the physical implementation without having to change your code.

Retrieve the Cache from the Container

The following example demonstrates how you can retrieve the object cache from the container:

ObjectCache cache = EnterpriseLibraryContainer.Current.GetInstance<ObjectCache>(
    "CacheName");

You should set the string value "CacheName" to the name you gave your cache when you configured it.

Adding Items to the Cache

The following code sample shows how to add an item to the cache. It also shows several options for using cache item policies.

object valueToSet = new Object(); // Set this to the value to add to the cache

// Example of an absolute expiration policy. 
// Item will expire in 2 minutes, regardless if it is accessed or not
var absoluteExpirationPolicy = new CacheItemPolicy{AbsoluteExpiration = DateTime.Now.AddMinutes(2)};

// Example of a sliding expiration cache item policy
// item will expire if not accessed for more than 2 minutes
var slidingExpirationPolicy = new CacheItemPolicy{SlidingExpiration = new TimeSpan(0, 0, 2, 0)};

// Example of a policy that defines that item will not expire. It will only be    // removed.
// if the cache becomes full. 
var notExpiringPolicy = new CacheItemPolicy();

// The add method will only add the item if it doesn't already exist
bool added = cache.Add("CacheKey", valueToSet, notExpiringPolicy);

// The set method will add or overwrite an item. 
cache.Set("CacheKey", valueToSet, notExpiringPolicy);

// When setting a cache item using the indexer, it will always be set to 
// infinite expiration
cache["CacheKey"] = valueToSet;

// The AddOrGetExisting method will try to add it if it doesn't already 
// exist. If it has added it, then it will return the added item
// else it will return the already cached item. 
var cachedValueOrValueToSet =  cache.AddOrGetExisting("CacheKey", valueToSet, 
    notExpiringPolicy);

Testing If an Item Is in the Cache

The following code example shows the recommended way to test if an item is already in the cache:

var cachedItem = cache["Cachekey"];
if (cachedItem == null)
{
   // Item was not cached
}
else
{
    // Item is cached
}

While you can use the Contains method to test if something is in the cache, this method is not recommended. Due to the multi-threaded nature of the cache, it is possible that the cached item is removed directly after calling the Contains method.

Using the Removed Callback

You can use the RemovedCallback to detect that an item is removed from the cache. The following example demonstrates how to use this:

// Specify that the ItemRemoved method should be called when the item gets removed
var policyWithRemovedCallBack = new CacheItemPolicy {RemovedCallback = ItemRemoved};

cache.Set("CacheKey", valueToSet, notExpiringPolicy);
cache.Remove("CacheKey");

private void ItemRemoved(CacheEntryRemovedArguments arguments)
{
    // The arguments object contains information about the removed item such as: 
    var key = arguments.CacheItem.Key;
    var removedObject = arguments.CacheItem.Key;
    var removedReason = arguments.RemovedReason;
}

These callbacks do not get serialized to isolated storage. When the application is closed, these callbacks are lost and will not be executed again when the application starts and these items are evicted from the isolated storage cache.

Using the Updated Callback

You can use the UpdatedCallback to detect that a cached item or its Cache Item Policy has changed. The following code sample shows how this works:

var policyWithUpdateCallBack = new CacheItemPolicy { UpdateCallback = ItemUpdated };
cache.Set("CacheKey", valueToSet, notExpiringPolicy);
cache.Set("CacheKey", changedValue, notExpiringPolicy);
private void ItemUpdated(CacheEntryUpdateArguments arguments)
{
    var key = arguments.Key;
    // The updated Cache Item allows you to make changes to the cached item
    var updatedCacheItem = arguments.UpdatedCacheItem;

    // The updated cache item policy allows you to make changes to the 
    // cache item policy
    var updatedCacheItemPolicy = arguments.UpdatedCacheItemPolicy;
    var removedReason = arguments.RemovedReason;
}

Next Topic | Previous Topic | Home

Last built: July 8, 2011