Share via


Clear Cache c#

Question

Friday, January 2, 2009 1:32 AM

 

Hi All,

Am having a problem here... Using Cache for storing records..

I want to clear the cache when page gets Redirect to other.., presently using below code

protected void Page_Unload(object sender, EventArgs e)
    { 
        if (Cache["List"] != null) Cache.Remove("List");
    }
I know above code will not work, couple of AutoPostBacks also happening. Please help me a solution to clear the Cache.
 

All replies (9)

Friday, January 2, 2009 10:34 AM ✅Answered

you can do in the global.asax in the application end event

Also i found a snippet to clear all the cache objects from here

http://www.aspdotnetfaq.com/Faq/How-to-clear-your-ASP-NET-applications-Cache.aspx

public void ClearApplicationCache()

    {

        List<string> keys = new List<string>();

 

        // retrieve application Cache enumerator

        IDictionaryEnumerator enumerator = Cache.GetEnumerator();

 

        // copy all keys that currently exist in Cache

        while (enumerator.MoveNext())

        {

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

        }

 

        // delete every key from cache

        for (int i = 0; i < keys.Count; i++)

        {

            Cache.Remove(keys[i]);

        }

    }


Saturday, January 3, 2009 1:03 AM ✅Answered

 

Thats looks gud, thank you...

Also, Cache["List"] = null; throws error.. please check at your end also.. better to use Cache.Remove("List");


Friday, January 2, 2009 2:39 AM

simply do

protected void Page_Unload(object sender, EventArgs e)
{ 
        if (Cache["List"] != null) 
          Cache["List"] = null;
}

Friday, January 2, 2009 3:07 AM

 

There is couple of AutoPostBacks happening... everytime this will clear the cache.. i need to aviod that...

Once the user get redirect to another page only, i need to clear it...


Friday, January 2, 2009 3:59 AM

Then write the code on the pageload of the page where you are redirecting from ur current page


Friday, January 2, 2009 4:56 AM

 

I forgot, page selection through menu is also there.. i need to check on every page for cache and clear it???


Friday, January 2, 2009 5:12 AM

Either do there

Or

Just in the code block where you redirect this way. Since you will have some event or condition where you do redirect So do it there

if (Cache["List"] != null)

          Cache["List"] = null;
Response.Redirect("Page2.aspx");

Friday, January 2, 2009 10:24 AM

 

MAK,

If I go for clearing cache at Application/Session end level.... what will be the better way to do....??


Saturday, January 3, 2009 1:34 AM

yes Correct. I thought it might work here since it works with Sessions.