How to clear cache in asp.net C#, with removing all caches

Lionsure 2020-09-19 Original by the website

Caching is to temporarily store frequently used data in memory so that the program does not frequently access the database or hard disk. Not only greatly improves the efficiency of program, and reduces the pressure on the database, but also reduces the number of times to access the hard disk. Caches are all at the cost of memory usage. After all, memory is limited, and unnecessary data should be removed in time. However, it is often not only a few in applications, so management is not very convenient. Fortunately, there is a way to remove all caches.

 

1. How to clear cache in asp.net C# (clear specified cache)

string cacheKey = "TestCache";

//Add cache
       Cache.Add(cacheKey, "Cache content", null, DateTime.Now.AddMinutes(30), TimeSpan.Zero, CacheItemPriority.High, null);

Cache.Remove(cacheKey);//C# clear cache

 

2. How to clear all caches in asp.net C#

IDictionaryEnumerator allCaches = HttpRuntime.Cache.GetEnumerator();

while (allCaches.MoveNext())
       {
              Cache.Remove(allCaches.Key.ToString());
       }
       Response.Write("Remove all caches!");