SoFunction
Updated on 2025-03-07

Summary of basic usage of cache in C#

This article initially explores the principles and applications of C# caching and analyzes and summarizes them with examples. These are very necessary for beginners of C# to master. The details are as follows:

1. Overview:

Caching application purpose: Caching is mainly to improve the reading speed of data. Because there is a traffic bottleneck between the server and the application client, when reading large-capacity data, using cache to directly serve the client can reduce the data interaction between the client and the server, thereby greatly improving the performance of the program.

1. Cache reference space:; The cache namespace mainly provides three operations: cache data objects, cache dependencies of objects, and cache dependencies of databases. In which cache any object uses a class Cache, but when the cache changes, the dependency processing of ordinary objects and database objects is different.

2. Manage cache class: Cache

The Cache class is used to store data objects and provides methods to edit these objects. The Cache class belongs to the dictionary class, which stores the data needed by users according to certain rules. The types of these data are not restricted, and can be strings, arrays, data tables, Datasets, and hash tables.
The advantage of using the Cache class is that when the cached data changes, the Cache class will invalidate the data and re-add the cached data, and then notify the application to report the cached update in a timely manner.

2. Detailed explanation of the method:

The Cache method mainly provides editing operations on cached data, such as adding, deleting, and modifying.

Add Add data to Cache object
Insert inserts data items into the cache, which can be used to modify existing data cache items.
Remove Remove cached data items in the Cache object
Get the specified data item from the Cache object. Note that the return is the Object type and requires type conversion.
GetType Gets the type of data item from the Cache object, and after judging the data type, it is convenient to convert it

The most important thing to note is the Add method, which uses syntax as follows:

public Object Add (
string key,
Object value,
CacheDependency dependencies,
DateTime absoluteExpiration,
TimeSpan slidingExpiration,
CacheItemPriority priority,
CacheItemRemovedCallback onRemoveCallback
)

When using the Add method, the above 7 parameters are required, and their representative meanings are as follows:
— The parameter "key" represents the key value of the cached data item and must be unique.
— The parameter "value" represents the content of the cached data and can be of any type.
— The parameter "dependencies" indicates the cached dependencies, which means that the cached content has expired. If there are no dependencies, set this value to NULL.
— The parameter "absoluteExpiration" is date-type data, indicating the time when the cache expires. The cache provided by .NET 2.0 can be used after it expires. How long it can be used depends on the setting of this parameter.
— The type of parameter "slidingExpiration" indicates a period of time interval, indicating how long the cache parameter will be deleted. This parameter is associated with the absoluteExpiration parameter.
— The parameter "priority" indicates the priority value for undoing the cache. The value of this parameter is taken from the enumeration variable "CacheItemPriority". Data items with low priority will be deleted first. This parameter is mainly used when cached exit objects.
— The parameter "onRemoveCallback" indicates the event called when the data object is deleted, and is generally used as a notification program.

The application code is as follows:

ArrayList myarray = new ArrayList();
        ("1.Learn the World 1");
        ("2. Learning World 1");
        ("3. Learning World 1");
        ("4. Learning World 1");
        string item = "This is a cache";
        Cache["item"] = item;//Assignment        (("item") + "<br/>");
 
        item = "Change a cached data";
        ("item", item);//Change cache value        (("item") + "<br/>");
 
 
        //("item"); //Remove cached value        //(("item") + "<br/>");
 
        (Cache["item"].GetType().Name + "<br/>");//GetType gets the cache data type        (("Array") + "<br/>");//GetType gets the cache data type 
 
        IDictionaryEnumerator bianli = ();//Transfer the entire cache        while (())
        {
          ( + "<br/>");
        }
        ("Get cache number:" + );
 
        if (Cache["Array"] == null)
        {// When the cache Array does not exist, add the cache, and the cache time is set to 5 seconds          ("Array", myarray, null, (5), , , null);
        }

3. Cache Dependency Class: CacheDependency Class

Function description:

The CacheDependency class is called a cache dependency class. Its specific meaning is that when the actual data of the cache object changes, it can promptly notify the cache object. For example, the cache object "Category" saves the data of an XML file. If the XML file changes, the system will update the content of the cache object "Category" in time through the CacheDependency class, so as to ensure that the user reads the latest data.

Code example:

The file is as follows:

<?xml version="1.0" encoding="utf-8" ?>
<book>
 <bookinfo>
  <name>Ancient British</name>
  <price>28.00</price>
 </bookinfo>
 <bookinfo>
  <name>Chinese History</name>
  <price>20.00</price>
 </bookinfo>
 <bookinfo>
  <name>Chinese History1232sdf2</name>
  <price>20.00</price>
 </bookinfo>
</book>

The background code is as follows:

private static CacheDependency Mydata;
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack)
      {
        DataSet ds = new DataSet();
        ((""));//Read the data in Xml        if (Cache["CXml"] == null)
        {
          //Create cache dependencies          Mydata = new CacheDependency((""));
          ("CXml", ds, Mydata, (10), , , null);
        }
      }
    }
 
    protected void Button1_Click(object sender, EventArgs e)
    {
      if ()
      {//Judge whether the cache is changed        ("The cache has changed, the time to change is"+);//Get the cache update time      }
      if (Cache["CXml"] == null)
      {// When the xml file is changed, the cache is loaded from the new load        DataSet ds = new DataSet();
        ((""));//Read the data in Xml        //Create cache dependencies        Mydata = new CacheDependency((""));
        ("CXml", ds, Mydata, (60), , , null);
      }
      this. = Cache["CXml"];
      this.();
    }