Archive

While adding or inserting an item into cache object, we add dependency object as well to ensure the cache is automatically invalidated if any change is detected in that dependent object like file, for example. Then, we again read or update that item from the original source to make sure the item is still fresh with data. This is one of the main reasons that really appeal the use of ASP.Net caching feature where one can decide about dependencies and expiry time policy. There are other properties also that can be used in combination to set the scope of cached object within time frame and location. See also HttpCacheability .

But today we will explore the CacheItemRemovedCallback delegate provided by ASP.Net. It is used to notify the application about cache removal or deletion with some reason. CacheItemRemovedReason enumeration is used as a parameter in call back method to tell the appropriate reason of removal.

Let’s take an example to know more about the CacheItemRemovedCallback delegate.

The first parameter specifies the cache key name that we used to store an item (an ArrayList collection values). Second parameter is the object that we stored in the cache. The third parameter is an enumeration which has enum values like Removed, Expired, Underused, and DependencyChanged.

In the above example, if any change is made in CacheDependentFile.txt file, the call back method is automatically fired, and the reason captured will be DependencyChanged. Try and see.

Important Point: When using a CacheItemRemovedCallback make sure that you make the callback method ("OnCachedItemRemoved " in the sample above) a static method.

This feature can be used in many cases like logging the reason why any cached item was removed from the cache, and many others depending upon the scenario.