Caching is a technology that stores frequently used data/information in memory so that the next time the same data/information is needed, it can be retrieved directly from memory instead of being generated again from the application.
Caching is very important in improving ASP performance because ASP pages and controls are dynamically generated. This is extremely important for interaction-related data, where response time is at a premium.
In media that needs to be accessed quickly, such as a computer's random access memory, caches place frequently used data. The ASP runtime contains key-value pairs called cached CLR objects. It is located within the application and is available through HttpContext and System.Web.UI.Page.
In some ways, caching and storing state objects are similar. However, the information stored in the state object is deterministic. For example, you can calculate the data stored in the state object, but the cached data is not deterministic.
Data is unavailable under the following circumstances:
If its life cycle has ended,
If the app frees its memory,
If for some reason the cache is not replaced.
You can use an indexer to access items in the cache, and it is possible to control the lifetime of objects in the cache and set the relationship between cached objects and their physical resources.
ASP provides the following different types of cache:
Output cache : The output cache can store a copy of the last rendered web page, or a partial page sent to the client. The next time the client requests the page, a cached copy of the page is sent to the client instead of regenerating the page, which saves time.
Data caching : Data caching refers to caching data from the data source. As long as the cache has not been replaced, the data will be obtained from the cache when requested again. When the cache is replaced, new data is fetched from the data source and the cache is filled again.
Object cache : Object cache is to cache the objects of the page, such as data-bound controls, etc. Cached data is placed in the server's memory.
Class Caching : The first time a web page or web service is run, the compiled page classes are assembled. The assembly is then cached on the server. The next time the page or service is requested, the cached assembly will be used. When the source code is changed, the CLR recompiles the assembly.
Configuration cache : Application configuration information is stored in a configuration file. The configuration cache stores configuration information in server memory.
In this tutorial, we will consider output caching, data caching and object caching.
Rendering a page may involve some complex processes, such as database access, rendering complex controls, etc. Output caching allows bypassing round trips to the server by caching data in memory. Even the entire page can be cached.
The OutputCache directive is responsible for output caching. It enables output caching and provides a certain degree of control over its behavior.
Syntax of the OutputCache directive:
<%@ OutputCache Duration="15" VaryByParam="None" %>
Place this directive under the page directive. This tells the environment that the page needs to be cached for 15 seconds. The following page load event handler will help confirm whether the page has been cached.
protected void Page_Load(object sender, EventArgs e){ Thread.Sleep(10000); Response.Write("This page was generated and cache at:" + DateTime.Now.ToString());}
The Thread.Sleep() method stops the process for a specific period of time. In this example, the thread is stopped for 10 seconds, so when the page is first downloaded, it takes 10 seconds. However, the next time you refresh the page, it won't take time because the page has already been fetched from the cache and won't be downloaded again.
The OutputCache directive has the following features when helping to control the behavior of the output cache:
property | value | describe |
---|---|---|
DiskCacheable | true/false | Describes whether output can be written to disk with cache. |
NoStore | true/false | Describes whether the "no store" cache header is sent. |
CacheProfile | String name | The name of the cache configuration file stored in web.config. |
VaryByParam | None*Parameter name | Use semicolon-separated string values in GET requests or variable values in POST requests. |
VaryByHeader | *Header file name | Might be a semicolon-delimited string specifying headers submitted by the client. |
VaryByCustom | Browser custom string | Notify ASP.NET of changes to the output cache via browser name version or client string. |
Location | Any Client Download Streaming ServerNone | Any: The page may be cached anywhere Client: The cached content is contained in the browser Download stream: The cached content is stored in the download stream and the server Server: The cache is only stored in the server None: No caching is allowed. |
Duration | number | The number of seconds for a page or operation to be cached. |
Let's add a text box and a button to the previous example, and add an event handler for this button.
protected void btnmagic_Click(object sender, EventArgs e){ Response.Write("<br><br>"); Response.Write("<h2> Hello, " + this.txtname.Text + "</h2>") ;}
Change the OutputCache directive:
<%@ OutputCache Duration="60" VaryByParam="txtname" %>
When the program executes, ASP caches the page based on the name in the text box.
The main aspect of data caching is data source control caching. We've discussed data source controls that represent data from a data source, such as a database or an XML file. These controls are derived from the abstract class DataSourceControl and have the following inherited properties for caching:
Cache Period—The time for the data source to cache data.
Cache expiration policy — defines the behavior of the cache when data in the cache expires.
Cache value dependency - defines a control value that automatically moves the data out of the cache when it expires.
Enable caching—You can confirm whether data is cached.
To demonstrate data caching, we create a new website and add a new web form to it. Add a SqlDataSource control to the database that connects to the data access tutorial.
In this example, we add a label to the page that displays the page's response time.
<asp:Label ID="lbltime" runat="server"></asp:Label>
Apart from this tag, the entire page is the same as the data access tutorial. Add an event handler to this page to download the time.
protected void Page_Load(object sender, EventArgs e){ lbltime.Text = String.Format("Page posted at: {0}", DateTime.Now.ToLongTimeString());}
The designed page should look like this:
When you execute the page for the first time, nothing different happens. Label display, every time the page is refreshed, the page will be reloaded, and the time change will be displayed on the label.
Next, set the EnableCaching property of the data source control to "true" and the Cacheduration property to "60". It will implement caching and the cache will expire every 60 seconds.
Every time it is refreshed, the timestamp will change. But if you change the data in the table within 60 seconds, it will not be displayed until the cache expires.
<asp:SqlDataSource ID = "SqlDataSource1" runat = "server" ConnectionString = "<%$ ConnectionStrings: ASPDotNetStepByStepConnectionString %>" ProviderName = "<%$ ConnectionStrings: ASPDotNetStepByStepConnectionString.ProviderName %>" SelectCommand = "SELECT * FROM [DotNetReferences]" EnableCaching = "true" CacheDuration = "60"> </asp:SqlDataSource>
Object caching provides greater flexibility than other caching technologies. You can use object caching to place any object in the cache. Objects can also be of any type - data types, network controls, classes, data settings objects, etc. These items can be added to the cache simply by assigning them a value name, as shown below:
Cache["key"] = item;
In order to insert objects in the cache, ASP provides the Insert() method. There are four overloaded versions of this method. Let’s take a look:
Overload | describe |
---|---|
Cache.Insert((key, value); | Insert into the cache in the form of key-value pairs, with the priority and life cycle being the default. |
Cache.Insert(key, value, dependencies); | Insert cache into the cache as key-value pairs, with default priorities and lifetimes, and cache dependencies linked to other files or content, so cache modifications are no longer limited. |
Cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration); | Indicate the validity period of the above configuration. |
Cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback); | Along with configuration it also allows setting the priority of cached content and delegation, indicating a method to be called when an object is removed. |
Dynamic lifecycle is used to remove a cache item that is not valid for any specified time span. The following code snippet saves a dependency-free cache item with a 10-minute sliding lifetime:
Cache.Insert("my_item", obj, null, DateTime.MaxValue, TimeSpan.FromMinutes(10));
Create a page using just a button and a label. Write the following code in the page load event:
protected void Page_Load(object sender, EventArgs e){ if (this.IsPostBack) { lblinfo.Text += "Page Posted Back.<br/>"; } else { lblinfo.Text += "page Created.<br/> "; } if (Cache["testitem"] == null) { lblinfo.Text += "Creating test item.<br/>"; DateTime testItem = DateTime.Now; lblinfo.Text += "Storing test item in cache "; lblinfo.Text += "for 30 seconds.<br/>"; Cache.Insert("testitem", testItem, null, DateTime.Now.AddSeconds (30), TimeSpan.Zero); } else { lblinfo.Text += "Retrieving test item.<br/>"; DateTime testItem = (DateTime)Cache["testitem"]; lblinfo.Text += "Test item is: " + testItem.ToString(); lblinfo.Text += "<br/>"; } lblinfo.Text += "<br />";}
When the page loads for the first time, it displays:
Page Created.Creating test item.Storing test item in cache for 30 seconds.
If you click the button again within 30 seconds, although the page is deleted, the label control will get the information from the cache, as shown below:
Page Posted Back.Retrieving test item.Test item is: 14-07-2010 01:25:04