The Most Efficient ASP.NET Cache Clearing Method

asp.net c# cache-control caching entity-framework

Question

I'm developing an ASP.NET/Umbraco-powered website that uses a lot of custom data driven by entity framework, and since it's a busy site, we have to cache a lot of the data queries (like keyword searches).

But in order for the new item to appear in the results when a user adds new data, I need to delete any previously cached searches (Searches, etc.).

I thus call the following method in my create, remove, and update methods:

public static void ClearCacheItems()
{
    var enumerator = HttpContext.Current.Cache.GetEnumerator();

    while (enumerator.MoveNext())
    {
        HttpContext.Current.Cache.Remove(enumerator.Key.ToString());
    }
}

Is it really that bad? I am unable to identify any way to clear the cached items.

1
19
6/2/2011 9:27:24 AM

Popular Answer

There is just a little "mistake" in your code; the technique you use to delete your cache is really the right one. The initial collection stays constant is as lengthy as the enumerator only is true.. Therefore, even if the code may generally function well, there may occasionally be minor flaws. It is best to use the following code, which does roughly the same thing without explicitly using the enumerator.

List<string> keys = new List<string>();
IDictionaryEnumerator enumerator = Cache.GetEnumerator();

while (enumerator.MoveNext())
  keys.Add(enumerator.Key.ToString());

for (int i = 0; i < keys.Count; i++)
  Cache.Remove(keys[i]);
11
6/2/2011 9:35:05 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow