The CacheItemRemoveCallBack is a callback that can be
attached to the items that are inserted in the Cache. The Callback can be fired
when you remove the item from the cache or when the item is automatically
removed due to some conditions like file change, database table change.
In order to put the cache dependency and callback on a cache item which is
dependent on the file you can do the following:
First you need to create the cache dependency on the file. This can
be done by the following code.
private void CreateMenu()
{
string menuPath = "MyFiles/Menu.xml";
DataSet ds = null;
if (Cache["Menu"] == null)
{
ds = new DataSet();
ds.ReadXml(Server.MapPath(menuPath));
// menu is created
Cache.Insert("Menu", ds, new System.Web.Caching
.CacheDependency(Server.MapPath(menuPath)),DateTime
.Now.AddMinutes(60),TimeSpan.Zero, System.Web.Caching
.CacheItemPriority.Default,new System.Web.Caching
.CacheItemRemovedCallback(CacheItemRemovedCallBack));
DisplayCacheCreationTime("Object was not in the
cache and created at:",DateTime.Now.ToLongTimeString());
}
else
{
// menu is created from the cache
DisplayCacheCreationTime("Object was in the cache",String.Empty);
}
}
Now, when I click the button I will add a new element in the XML file
which will automatically remove the cache key from the cache object.
// this button will write xml to the Menu.xml file
protected void Button1_Click(object sender, EventArgs e)
{
string menuPath = "MyFiles/Menu.xml";
XmlDocument xDoc = new XmlDocument();
xDoc.Load(Server.MapPath(menuPath));
XmlElement root = xDoc.DocumentElement;
XmlElement newNode = xDoc.CreateElement("MenuItem");
newNode.InnerText = "Services";
root.InsertBefore(newNode, root.FirstChild);
xDoc.Save(Server.MapPath(menuPath));
}
And finally the callback method is fired.
private void CacheItemRemovedCallBack(string key, object value
, CacheItemRemovedReason reason)
{
// Do
whatever
}
It is not a good idea to insert the items to the cache
object inside the CacheItemRemovedCallBack method since, you might not
require that removed item right away and in that scenario you will only be
wasting resources.
powered by IMHO 1.3