CacheItemRemovedCallback in ASP.NET

CacheItemRemovedCallback is a delegate that provides notification to a page when an item has been removed.

Introduction

CacheItemRemovedCallback is a delegate that provides notification to a page when an item has been removed.

Let's see how we can write code for CacheItemRemovedCallback.

Step 1: First of all we will create a new ASP.NET application.

Step 2: Now will add two buttons in the Default.aspx page. See the following image. One button will save the cache and the other will remove an item from the Cache.


CacheItemRemovedCallback_1.png 

Step 3: Now will write code inside the code-behind page. If you see the following highlighted code then you will understand how it will work.

In the first line of highlighted code we declare a callback delegate. In the next highlighted line we are initializing the callback delegate. It will be called when our cache time expires. In the following code we use 60 seconds:

static bool itemRemoved = false;
static CacheItemRemovedReason reason;
CacheItemRemovedCallback onRemove = null;

public void RemovedCallback(String k, Object v, CacheItemRemovedReason r)
{
            itemRemoved = true;
            reason = r;
}
protected void addCache_Click(object sender, EventArgs e)
{
            itemRemoved = false;
            onRemove = new CacheItemRemovedCallback(this.RemovedCallback);
            if (Cache["Key1"] == null)
                Cache.Add("Key1", "Value 1", null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.High, onRemove);
            Label1.Text = "Cache has been set.";
}
protected void removeCache_Click(object sender, EventArgs e)
{
            if (Cache["Key1"] != null)
                Cache.Remove("Key1");
            Label1.Text = "Cache has been removed.";
}

 

Step 4: You can only understand this concept while debugging the application; you will see how RemovedCallback will be called.

Happy Coding.