I. cache Overview
Cache is a technology widely used in computers to improve performance. It retains data with high access frequencies or high construction costs in the memory, access to the data within the cache validity period can be directly read from the memory without repeated execution. This saves both system resources and
This accelerates the program running speed. For web forms, the caching technology is extremely important because the speed of data transmission over the Internet may be very slow. By caching data, web form can greatly improve the response speed and performance of applications, thus improving transmission performance.
In web form, the cache is used to retain pages or data in HTTP requests and reuse them without re-creation .. Net has three types of caches available for web form:
· The page outputs cache the entire page of the request.
· The page fragment caches Custom User Controls on the request page.
· The page data cache program caches objects or data on the page.
How should we use these three caches differently? The following describes how to use these instances.
Ii. Cache Usage
1. Use of page output Cache
As the name implies, the page output cache caches the entire page. In the future, requests to this page will be output by the cache without executing the code to create this page. Page output cache is the most common Cache Technology in ASP. NET. In websites with high traffic volumes, caching pages with High Access frequency only for one minute at a time brings huge throughput gains.
It is easy to start the page output cache function. You only need to use the page compilation command outputCACHE:
<% @ Outputcache duration = "time" varybyparam = "none" %>
In this command, outputcache indicates to put the page into the cache. The duration parameter sets the cache validity period in seconds. varybyparam sets the cache for requests that change with the name/value pair value in the query string. For specific applications, see Example 1. For varybyparam applications, see Example 2.
Example 1: pagecache. aspx
<% @ Outputcache duration = "30" varybyparam = "NONE" %>
<% @ Page Language = "VB" %>
<HTML>
<Head>
<Title> page output Cache Technology </title>
<SCRIPT runat = "server">
Sub page_load (OBJ as object, e as eventargs)
'Output page generation time
Lblmessage. Text = "Welcome! The current time is: "& datetime. Now. tostring ()
End sub
</SCRIPT>
</Head>
<Body>
<Form ID = "form1" method = "Post" runat = "server">
<Div align = "center">
<Font style = "font-size: 12pt; font-weight: bolder; color: Red"> page output Cache Technology </font>
<HR size = 1>
<Asp: Label id = "lblmessage" runat = "server"/>
</Div>
</Form>
</Body>
</Html>
This is a simple example of using the page output cache. Its running result shows the page generation time on the screen. The compile command outputcache indicates that the page is cached for 30 seconds. The value of varybyparam is none, indicating that the page does not change with any get or post parameters. During the cache validity period, requests for this page are cached. After 30 seconds, the page is removed from the cache and the next request is processed explicitly and the page is cached again. In this example, the current time will not change no matter how the cache is refreshed within 30 seconds, which fully indicates that the page is not actually executed during the cache period, it only reads the cache page directly to respond to client requests. The page will be re-executed and a new current time will be generated only when the cache expires and then requests again.
In the page output cache, how should the varybyparam parameter be used? When developing ASP. NET applications, we often need to pass parameters and use these parameters for conditional queries. Parameters can be transmitted by file name, such as pageparamcache. aspx? Name = Jack indicates that the parameter name with the value "Jack" is passed. Then, how can we cache the entire page based on the parameter value? The varybyparam parameter is used here. ASP. net checks whether the requested page is cached Based on the passed parameter value. If the parameter value is different, Asp. net registers a cache miss, that is, the page is not found in the cache, and then re-executes the page and stores it in the cache. If the parameters are the same, ASP. NET will directly read the output from the cache. This means that the same page can generate different cache pages based on different parameters/values. For specific applications, see Example 2.
Example 2: pageparamcache. aspx
<% @ Outputcache duration = "60" varybyparam = "name" %>
<% @ Import namespace = "system. Data" %>
<% @ Import namespace = "system. Data. sqlclIENT "%>
<HTML>
<Script language = "VB" runat = "server">
Sub page_load (SRC as object, e as eventargs)
Dim myconnection as sqlconnection
Dim mycommand as sqldataadAPTer
Dim ds as Dataset
Dim strname as string
Dim strsql as string
Querystate = request. querystring ("name ")
If querystate = nothing
'Query unused Parameters
Strsql = "select * from articles"
Else
'Query with Parameters
Strsql = "select * from articles where name = '" & strnmae &"'"
End if
Myconnection = new sqlconnection ("Server = localhost; uid = sa; Pwd =; database = article ")
Mycommand = new sqldataadapter (strsql, myconnection)
DS = new dataset ()
Mycommand. Fill (DS, "articles ")
Dbgridcontent. datasource = new dataview (Ds. Tables ("articles "))
Dbgridcontent. databind ()
Lblmessage. Text = datetime. Now. tostring ()
End sub
</SCRIPT>
<Body>
<Div align = "center">
<Font style = "font-size: 12pt; font-weight: bolder; color: red"> use the page output cache with parameters </font>
<Br> by Author: <br>
<Table cellspacing = "0" cellpadding = "3" width = 700>
<Tr>
<TD> <a href = "pageparamcache. aspx? Name = Zhang San "> Zhang San </a> </TD>
<TD> <a href = "pageparamcache. aspx? Name = Li Si "> Li Si </a> </TD>
<TD> <a href = "pageparamcache. aspx? Name = Wang Wu "> Wang Wu </a> </TD>
<TD> <a href = "pageparamcache. aspx? Name = "> </a> </TD>
<TD> <a href = "pageparamcache. aspx? Name = Liu Qi "> Liu Qi </a> </TD>
</Tr>
</Table>
<Asp: DataGrid id = "dbgridcontent" runat = "server"/> <br>
<I> last generation time: </I> <asp: Label id = "lblmessage" runat = "server"/>
</Div>
</Body>
</Html>
In Example 2, the value of varybyparam is name, which indicates that the page is cached Based on the name value. When you click the link of a given name for the first time, a new timestamp is generated at the bottom of the page. After that, when you resubmit a request for the name within one minute, the original timestamp will be obtained, indicating that the request has been cached. When you click the link of another name, the system first looks for the cache page stored with this name value. If not, the page is re-executed and cached. If yes, the cache page is output directly. In the case given in example 2, pageparamcache. aspx can have up to five different page output caches to respond to five link requests with different parameter values.
If more than one parameter is passed, different cache pages are generated on the request page even if the string parameter and value are the same but in different order. For example, pageparamcache? First = Chris & last = Payne and pageparamcache? Last = Payne & First = Chris although the parameters are identical, two different cache pages are generated due to different order. You can test the specific application by yourself.
2. Use of page segment Cache
Sometimes caching the entire page is not feasible-you may have to create or customize each part of the page for each request. In this case, it is generally worthwhile to identify objects or data that are highly cost-effective and suitable for caching. Once these items are identified, you can create them once and then cache them for a period of time. In addition, the fragment cache can be used to cache the area of the page output. In ASP. NET, the page fragment cache is generally used to store Custom User Controls.
For example, a pageTo bind the last 10 news records to the DataGrid, and also count the page traffic to the database. Obviously, the operation to read news and bind the DataGrid should be put into the cache, because news updates are not frequent, which can avoid frequent access to the database. However, page access statistics cannot be cached. Otherwise, page requests within the cache validity period will be ignored. The best way to solve this "Conflict" is to use the page fragment cache. In Example 3, we define the SQL query and bind DataGrid operation as the user control (lastednews. and put it into the cache, while the parent page (controlparentcache. aspx) does not cache for real traffic statistics.Database
Example 3: controlparentcache. aspx on the parent page
<% @ Register tAGPRefix = "Zhao" tagname = "lastednews" src = "lastednews. ascx" %>
<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en">
<HTML>
<Head>
<Title> page segment cache </title>
<SCRIPT runat = "server">
'Count page access times and store them to the database visitor table
Sub page_load (OBJ as object, e as eventargs)
Dim myconnection as new sqlconnection ("Server = localhost; uid = sa; Pwd =; database = News ")
Myconnection. open ()
Dim mycommand as new sqlcommand
Dim mydatareader as sqldatareader = mycommand. executereader ()
Dim intvisit as integer = mydatareader. Item ("visittimes") + 1
Myconnection. Close ()
Mycommand = new sqlcommand ("Update visitor set visittimes =" & intvisit, myconnection)
Mycommand = nothing: mydatareader = nothing: myconnection = nothing
End sub
</SCRIPT>
</Head>
<Body>
<Form ID = "form1" method = "Post" runat = "server">
<Div align = "center">
<Font style = "font-weight: bolder; font-size: 12pt; color: Red"> 10 recent news </font>
<HR size = "1">
<ZHAO: lastednews runat = "server" id = "defaultnewsstock"/>
</Div>
</Form>
</Body>
</Html>
Example 3: User Control lastnews. ascx
<% @ Outputcache duration = "60" varybyparam = "*" %>
<SCRIPT runat = "server">
'Generate the DataGrid
Sub page_load (OBJ as object, e as eventargs)
'Bind the dataview record set to the DataGrid
Dbgridlastednews. datasource = loaddataview ()
Dbgridlastednews. databind ()
End sub
Function loaddataview () as dataview
'Define the connection and open the connection
Dim myconnection as new sqlconnection ("Server = localhost; uid = sa; Pwd =; database = News ")
Myconnection. open ()
'Perform the query operation and fill the result record set in dataview.
Dim mycommand as sqlclient. sqldataadapter = new sqlclient. sqldataadapter ("select top 10 * from news order by id desc", myconnection)
Mycommand. Fill (DS, "news ")
Loaddataview = new dataview (Ds. Tables ("news "))
Mycommand. Dispose ()
End Function
</SCRIPT>
<Asp: DataGrid id = "dbgridlastednews" runat = "server"> </ASP: DataGrid>
In Example 3, because we put the code for traffic statistics in the page loading function page_load () on the parent page, we cannot cache the parent page. In the definition file lastednews. ascx of the user control, we can clearly see that it is cached for 60 seconds. In this way, the page_load () function can always be executed whenever the parent page is loaded, and the user control bound to the DataGrid can be directly read from the cache within the cache validity period. By using the page fragment cache, We Can cache user controls while maintaining the dynamic attributes of the parent page, achieving a "win-win" situation ".
3. Use of page data cache
In general, the page data cache adds objects to the cache. We can think back to the process of creating a DataGrid object: Create a sqlconnection. Open sqlconnection. Create a sqldataadapter. Run the sqldataadapter with the SQL parameter to fill the datasetà and bind it to the DataGrid, creating a DataGrid in detail requires at least six steps, which not only reduces the program execution speed, but also consumes system resources that are not required. How nice it is to cache the results (such as dataset) after completing these operations! In fact, the most common purpose of page data cache is to cache the results returned by the database so that it can be easily and quickly bound to the DataGrid during the cache period.
Let's take a look at Example 4. Example 4: Use the cache class to cache data returned from the database.
Example 4: objectcache. aspx
<% @ Page Language = "VB" %>
<@ Import namespace = "system. Data" %>
<@ Import namespace = "system. Data. sqlclient" %>
<SCRIPT runat = "server">
Sub page_load (OBJ as object, e as eventargs)
If ont page. ispostback then
Createdata ()
End if
End sub
Sub createdata
Dim source as dataview
Assign the value of dataview in the cache to source
Source = cache ("dataview ")
If the cache is empty (that is, the first execution or cache expiration)
If source is nothing then
'Create and open the connection
Dim myconnection as sqlconnection
Myconnection = new sqlconnection ("Server = localhost; uid = sa; Pwd =; database = News ")
Myconnection. open ()
Dim mycommand as sqldataadapter
Mycommand = new sqlclient. sqldataadapter ("select * from news order by id desc", myconnection)
Mycommand. Fill (DS, "news ")
Source = new dataview (Ds. Tables ("news "))
Cache ("dataview") = Source
'Shows the DataGrid generation method information
Lblmessage. Text = "explicitly created dataset"
Else
Lblmessage. Text = "dataset retrieved from cache"
End if
Dbgridnews. datasource = Source
Dbgridnews. databind ()
End sub
<HTML> <body>
<Form runat = "server" id = "form1">
<Asp: DataGrid id = "dbgridnews" runat = "server"/>
<HR size = 1>
<Asp: Label id = "lblmessage" runat = "server"/>
</Form>
</Body>
When Example 4 is loaded for the first time, the page fills in the data retrieved from the database to dataset, binds it to the DataGrid, and stores it in the cache. In the future, page requests during the data cache period can obtain data from the cache, And the execution speed will naturally be greatly improved.
Compared with the previous two cache technologies, page data caching has three major advantages: first, it can cache any object, you do not need to cache the entire page or user control, but can cache more carefully. Second, the cache class allows you to use the dynamic expiration time (sliding EXPIration ). Finally, you can set dependencies for objects placed in the cache class ). This means that you can set the cached data to depend on another item. The cached DataGrid can depend on the underlying data. When the source data changes, the cached DataGrid will be voided and a new DataGrid will be created.
Iii. How to efficiently use the Cache Technology
The cache technology can greatly improve the performance of web forms. When the load is very high, even if the cache time is very short, the effect is very obvious. Usually, there is a lot of information that can be cached, including the data retrieved from the database or files, the results of complex computers, and application settings.
Although this article describes several benefits of using the cache, it is not suitable for using the cache at any time. For example, you must provide the latest stock quotation page. Unless enough dependency is set, it will be very bad to use the cache in this case, because if the cache is set, then, visitors cannot obtain the latest stock data in time during the page cache.