Reloading expired items

The Caching Application Block provides extensibility points at every level; imagine a scenario where a cache item has to be reloaded as soon as it expires. The ICacheItemRefreshAction interface defines the contract to cater to such requirements; we can implement a custom refresh action and pass it while adding the item to the cache.

The following code snippet shows the definition of ICacheItemRefreshAction interface:

namespace Microsoft.Practices.EnterpriseLibrary.Caching
{
public interface ICacheItemRefreshAction
{
void Refresh(string removedKey, object expiredValue, CacheItemRemovedReason removalReason);
}
}

The following code snippet is a sample skeleton structure to reload the expired item by implementing the ICacheItemRefreshAction interface:

[Serializable]
public class BookCacheItemRefreshAction : ICacheItemRefreshAction
{
public void Refresh(string removedKey, object expiredValue, CacheItemRemovedReason removalReason)
{
//Item removed from cache with the specified removal reason
//Refresh the cached item
}
}

The BookCacheItemRefreshAction class implements the ICacheItemRefreshAction interface. We have to provide the custom reload logic for the expired item in the Refresh method.

The following code snippet shows how to leverage the BookCacheItemRefreshAction class while adding items to cache:

BookCacheItemRefreshAction refreshAction = new BookCacheItemRefreshAction();
this.cacheManager.Add(book.ID.ToString(), book, CacheItemPriority.High, refreshAction, new SlidingTime(TimeSpan.FromMinutes(2)));

We are creating an instance of BookCacheItemRefreshAction and passing this object while invoking the Add method. Now, whenever the cached item expires the Refresh method will be invoked, this allows us to identify the cached item using the key. Additionally, it also provides the value of the expired item and the removal reason.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.182.66