C # Cache Technology

Source: Internet
Author: User
Document directory
  • 16.1.1 system. Web. caching Overview
  • 16.1.2 composition of classes in the system. Web. caching namespace
  • 16.2.1 Function Description
  • 16.2.2 syntax definition
  • 16.2.3 detailed explanation of the Method
  • 16.2.4 attribute details
  • 16.2.5 typical application: implement the data cache quick reading Function

The cache is mainly used to speed up Data Reading. Because there is a traffic bottleneck between the server and the application client, when reading large data volumes, cache is used to serve the client directly, which can reduce the data interaction between the client and the server, this greatly improves the program performance.

In this chapter, the namespace "system. web. beginning with caching, we will introduce in detail the cache classes and operation methods provided by the framework. They mainly involve three technical points: simple data cache, data cache dependency, and database cache dependency, finally, we will demonstrate an instance that fully uses cache for Data Reading. The process is described in 16-1.

:

Figure 16-1 Description of the cache namespace

16.1 introduction to system. Web. caching

This section describes the general introduction and composition of the cache namespace and provides an overview of system. Web. caching.

16.1.1 system. Web. caching Overview

System. Web. caching is used to manage the cache namespace. Cache is to temporarily Save the server data on the client for easy reading. The parent space of the cache namespace is "system. Web". It can be seen that the cache is usually used for Web site development, including development in the B/S project. The cache design mainly takes into account that the network bandwidth may delay data submission and re-sending. If you save the data on the client, you can directly read the data from the client, in this way, the data is extracted locally and will not be affected by the network.

The system. Web. caching namespace provides all the cache-related operation classes, including which classes will be detailed in the next section.

16.1.2 composition of classes in the system. Web. caching namespace

The cache namespace provides three operations: cache data objects, object cache dependencies, and database cache dependencies. Any cached object uses a class cache, but when the cache changes, the dependencies between common objects and database objects are different.

Figure 16-2 lists the cache deployment in a three-tier structure. The two dependent classes cachedependency and sqlcache dependency mainly change the cache data that has changed and serve as a notification. When the data is not cached, use the cache class to add it.

The following describes the cache classes used in the figure based on the deployment in Figure 16-2. Descriptions of these classes are shown in Table 16-1.

 

Figure 16-2 Deployment of cache in a layer-3 Structure

Table 16-1 classes in the cache namespace and their descriptions

Class Name

Description

Cache

Edit a cache object. operations include adding, deleting, and modifying a cache object.

Cachedependency

The dependency of the basic cache object. When the basic object changes, the cached content is updated.

Sqlcachedependency

The dependency of the database cache object. When the data in the database changes, the cache content is updated.

16.2 Cache Management class: cache class

The cache class is used to store data objects and provides methods to edit these objects. This section describes the methods contained in the cache class and how to use these methods to cache data objects.

16.2.1 Function Description

The cache class is a dictionary class that stores user-required data according to certain rules. The data types are unrestricted, including strings, arrays, data tables, dataset, 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 timely updates to the cache.

16.2.2 syntax definition

The syntax of the cache class is defined as follows:

Public sealed class cache: ienumerable

Through its definition, we can find that the cache class is a class defined by "sealed", indicating that this class is sealed and cannot be inherited. The cache class also inherits the ienumerable interface, which allows enumeration of data in the set.

The cache lifecycle ends with the completion of the application domain activity. That is to say, the cache will remain as long as the application domain is still active, because each application domain creates a cache instance. The instance information is obtained through the cache attribute of the httpcontext object or the cache attribute of the page object.

The following code demonstrates how to add array data to the cache:

Arraylist myarray = new arraylist (); // create an array of data

Myarray. Add ("1. Learning Garden ");

Myarray. Add ("2. Communication Forum ");

Myarray. Add ("3. Help ");

Cache. Add ("category", myarray); // Add the array to the cache

16.2.3 detailed explanation of the Method

Cache methods mainly provide editing operations for cache data, such as adding, deleting, and modifying. The most common methods and their descriptions are shown in Table 16-2.

Table 16-2 main cache methods and descriptions

Name

Description

Add

Add data to cache object

Insert

Insert a data item to the cache to modify an existing data cache item.

Remove

Remove cached data items from the cache object

Get

Obtain the specified data item from the cache object. Note that the returned data type is object and type conversion is required.

GetType

Obtain the data item type from the cache object and determine the data type for easy conversion.

Getenumerator

Cyclically access the cached data items in the cache object. Note that the return type is "idictionaryenumerator"

Tip: to modify the cache data, you only need to assign a value to the cache again.

Note that the add method uses the following syntax:

Public object add (

String key,

Object value,

Cachedependency dependencies,

Datetime absoluteexpiration,

Timespan slidingexpiration,

Cacheitempriority priority,

Cacheitemremovedcallback onremovecallback

)

When the add method is used, the preceding seven parameters are required. Their meanings are as follows:

-The "key" parameter indicates the key value of the cached data item, which must be unique.

-The "value" parameter indicates the content of the cached data, which can be of any type.

-The "dependencies" parameter indicates the cached dependency, that is, this change means that the cached content has expired. If there is no dependency, you can set this value to null.

-The "absoluteexpiration" parameter indicates the cache expiration time ,. the cache provided by NET 2.0 can be used after expiration. The setting of this parameter depends on how long the cache can be used.

-The type of the parameter "slidingexpiration" indicates a period of time, 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 revoking the cache. The value of this parameter is taken from the enumerated variable "cacheitempriority". Data items with low priority will be deleted first. This parameter is mainly used when the cache exits the object.

-The onremovecallback parameter indicates the events called when the data object is deleted in the cache. It is generally used as a notification program.

The following code demonstrates how to apply these methods to the cache class. When using this code, you must note that the arraylist object is used in the code, so you need to add the namespace "system. when using the cache category, you forget to add the namespace "system. web. caching ".

Protected void page_load (Object sender, eventargs E)

{

Arraylist myarray = new arraylist (); // create an array of data

Myarray. Add ("1. Learning Garden ");

Myarray. Add ("2. Communication Forum ");

Myarray. Add ("3. Help ");

// Add the array to the cache-use the Add Method

Cache. Add ("category", myarray, null, datetime. Now. addseconds (60), timespan. Zero, cacheitempriority. Normal, null );

Myarray [1] = "2. "; // modify the array data

Cache. insert ("category", myarray); // use the insert method to modify the cached data

String tmpstr = "this is a temporary data ";

Cache ["tmpdata"] = tmpstr;

// Use the get method to obtain cached data

Response. Write (Cache. Get ("tmpdata"). tostring () + "<br/> ");/

Cache ["tmpdata"] = "this is a temporary string"; // a new cache Assignment Technique

Response. Write (Cache. Get ("tmpdata"). tostring () + "<br/> ");

// Use the GetType method to determine the type of cached data

If (Cache ["category"]. GetType (). Name = "arraylist ")

Response. Write ("type is array ");

// Use the getenumerator method to traverse the cached data

Idictionaryenumerator mycache = cache. getenumerator ();

While (mycache. movenext ())

Response. Write (mycache. Value + "<br/> ");

Cache. Remove ("tmpdata"); // use the remove method to remove cached temporary data

}

Tip: when using the GetType method, to determine the type, you need to use the object. GetType (). Name attribute to obtain the type name.

The running result of the above Code is as follows:

This is a temporary data

This is a temporary string

The type is array. This is a temporary string.

System. Collections. arraylist

When reading data of the arraylist type, the system. Collections. arraylist object is retrieved because no type conversion is performed. This document describes how to read the details of an array in the instance at the end of this section.

16.2.4 attribute details

Cache attributes are used to obtain basic information about cached data, such as the total number of cached items and cache items at a specified position. This book mainly introduces two attributes: Count and item.

Count is used to obtain the total number of items in the cache. The usage is as follows:

Response. Write (Cache. Count );

Item is used to return the content of a specified item. Generally, classes that inherit the "ienumerable" interface have such attributes. Note that the items must be wrapped in. The usage is as follows:

Response. Write (Cache ["category"]. tostring ());

16.2.5 typical application: implement the data cache quick reading Function

Cache is mainly used to cache data that is frequently used and does not need to be updated frequently. In this example, a directory list is cached. For ease, the list content is not read from the database, but saved in an arraylist object.

The purpose of this example is to fill the directory list in the drop-down box. When the cache fails, the contents of the directory list are blank. The demo procedure is as follows.

Create a website in vs2005 and name it "cachesample ".

Open the default. aspx page generated by default, and add a drop-down list box and a button to it.

Press F7 to switch to the Code view on the page. Do not forget to reference the namespace. The Code is as follows:

Using system. Web. caching;

Using system. collections;

In the "page_load" event, check whether the directory cache exists. If not, add the directory to the cache. The detailed code is as follows. The directory list is saved for 5 seconds.

Protected void page_load (Object sender, eventargs E)

{

If (! Page. ispostback)

{

Arraylist myarray = new arraylist (); // assume that the content of arraylist comes from the database.

Myarray. Add ("Ancient History ");

Myarray. Add ("Contemporary Literature ");

Myarray. Add ("Popular Novels ");

Myarray. Add ("Martial Arts Novels ");

If (Cache ["categorys"] = NULL) // determines whether a cache exists.

{

// If the cache does not exist, add -- the storage duration is 5 seconds.

Cache. Add ("categorys", myarray, null, datetime. Now. addseconds (5 ),

Timespan. Zero, cacheitempriority. Normal, null );

}

}

}

Return to the design view, double-click the button control, and switch to the Event code of the button.

In the double-click event of the button, you need to determine whether there is a directory cache. If yes, the directory content is displayed in the drop-down box. If no, the drop-down box is cleared. The Code is as follows:

Protected void button#click (Object sender, eventargs E)

{

If (Cache ["categorys"]! = NULL) // determine whether the cache is invalid

{

// If it does not expire, the cache list is taken out. Pay attention to type conversion.

Dropdownlist1.datasource = (arraylist) cache ["categorys"];

Dropdownlist1.databind ();

}

Else

{

Dropdownlist1.items. Clear (); // clear the list if it has expired

}

}

Press Ctrl + S to save all the code and press F5 to run the program. If you click the button within five seconds, the directory list is displayed normally. If the number of seconds is exceeded, the cached object does not exist. Therefore, the content of the drop-down list box is empty.

This section describes how to use the cache class. The cache dependency content is not involved, that is, whether the cache changes as the actual data changes. The next section describes the detailed implementation of cache Dependencies by studying the "cachedependency" class.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.