Using cache can provide enormous performance benefits. To get them, however, we, as developers, should manage cache in a good, determined way. General way of cache management is:
1. Determine keys (will be represented in string) to each information group (example: for category domain objects use category, for a specific category use category_{id}). Use this key everywhere in your code, don't change (don't use category somewhere and Category in another place), you can constant string variables for this purpose.
2. When you get data first check whether it is in cache already; if yes, take it else get from your datasource then immediately add that data to the cache with the key.
3. Write a global method that takes a prefix, to purge cache items has the prefix
As an example: Below the code method that takes data from datasource (never mind its domain, just focus on its purpose):
public static int GetIhalelerCount()
{
int articleCount = 0;
//construct your key
string key = "tenders_approvedCount_" + categoryID.ToString();
//check whether it is on cache or not, if yes, take it
if (BaseDomain.Settings.EnableCaching && BizObject.Cache[key] != null)
{
articleCount = (int)BizObject.Cache[key];
}
//at this point, it is not in the cache, get it from datasource
//and insert it to the cache with your predetermined key
else
{
articleCount = SiteProvider.Provider.GetApprovedIhalelerCountByCategory(categoryID);
BaseDomain.CacheData(key, articleCount);
}
return articleCount;
}
The CacheData method:
protected static void CacheData(string key, object data)
{
//checks whether data is null or not, because in the case
//null exception is thrown
if (data != null)
{
HttpContext.Current.Cache.Insert(key, data, null,
DateTime.Now.AddSeconds(10), TimeSpan.Zero);
}
}
We need also a
PurgeCacheItems method to clean unnecessary data. This method is generally used in
Delete, Update, Insert methods because after this modifications data at hand become obsolete.
protected static void PurgeCacheItems(string prefix)
{
prefix = prefix.ToLower();
List itemsToRemove = new List();
IDictionaryEnumerator enumerator = HttpContext.Current.Cache.GetEnumerator();
while (enumerator.MoveNext())
{
if (enumerator.Key.ToString().ToLower().StartsWith(prefix))
itemsToRemove.Add(enumerator.Key.ToString());
}
foreach (string item in itemsToRemove)
{
HttpContext.Current.Cache.Remove(item);
}
}
In PurgeCacheItems, to get cache's content take enumeration of it by using GetEnumerator() method and iterate through it. You can also use itemsToRemove list above to list in an .aspx page, like:
protected void Page_Load(object sender, EventArgs e)
{
IDictionaryEnumerator enumerator = HttpContext.Current.Cache.GetEnumerator();
while (enumerator.MoveNext())
{
Label1.Text += enumerator.Key.ToString() + "
";
Label2.Text += enumerator.Value.ToString() + "
";
}
}
Hope, this helps.