Notifying an Application When an Item Is Deleted from the Cache
ASP.NET provides the CacheItemRemovedCallback delegate. It defines the signature to use when you write event handlers to respond when an item is deleted from the cache. ASP.NET also provides the CacheItemRemovedReason enumeration, which you can use to make event handlers dependent upon the reason the item is deleted.
To notify an application when an item is deleted from the cache
Create a local variable that raises the event for the CacheItemRemovedCallback delegate. For example, the following code creates an
onRemove
local variable of typeCacheItemRemovedCallback
.private static CacheItemRemovedCallback onRemove = null;
Note The variable must be of this type to be used in the onRemoveCallback parameter of the Cache.Add or Cache.Insert method in step four.
Create an event handler to respond when the item is removed from the cache. For example, the following code sets the static Boolean
itemRemoved
to true, and the static CacheItemRemovedReasonreason
to the value passed when the item is removed from the cache.Note Using the members of the CacheItemRemovedReason enumeration to create conditional code for the method in this step is an option open to you.
CacheItemRemovedReason reason; public void RemovedCallback(string key, object value, CacheItemRemovedReason callbackreason) { reason = r; } [Visual Basic] Dim reason As CacheItemRemovedReason Public Sub RemovedCallback(key As String, value As Object, reason As CacheItemRemovedReason) reason = r End Sub
Note This event handler must use the same signature as the CacheItemRemovedCallback delegate. This code assumes that you have created two static variables:
itemRemoved
of type Boolean and
reason
of type CacheItemRemovedReason.
Create an instance of the CacheItemRemovedCallback delegate that calls the event handler. The following code calls the method created in step two.
onRemove = new CacheItemRemovedCallback(this.RemovedCallback);
Add the item to the Cache by using either the Cache.Add method or Cache.Insert method. You must specify the local variable, created in step one, in the onRemoveCallback parameter. The following code uses the Insert method to add an item to the cache with a key of
"MyData1"
and a value ofSource
. It defines theonRemove
variable in the onRemoveCallback parameter.Cache.Insert("MyData1", Source, null, DateTime.Now.AddMinutes(2), NoSlidingExpiration, CacheItemPriority.High, onRemove);
When the item added in step four is removed from the Cache for any reason, the
RemovedCallback
method is called, and the code within it can be accessed to render new content to a requesting client or to notify your application in a way you choose as appropriate.For a full, working example, see documentation for the CacheItemRemovedCallback delegate.
See Also
Caching Application Data | Adding Items to the Cache | Retrieving Values of Cached Items | Deleting Items from the Cache