May 13, 2021 ASP.NET
Caching is a technique 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 rather than generated from the application.
Caching is important in terms of improving ASP performance because ASP pages and controls are generated dynamically. T his is extremely important for interactive data because response times are valuable.
In media that requires fast access, such as random access memory for computers, caches place frequently used data. T he RUN time of the ASP contains a key-value pair of CLR objects called caches. I t is located within the application and is available through httpcontext System.Web.UI.Page applications.
In some ways, cache and storage state objects are similar. H owever, the storage information for state objects is determinable, for example, you can calculate the data stored in state objects, but the cached data is indeterminate.
Data is not available in the following cases:
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 the connection between the objects that set the cache and their physical resources.
ASPs offer several different types of caches:
In this tutorial, we'll consider output caches, data caches, and object caches.
Rendering a page can involve complex processes, such as database access, rendering complex controls, and so on. T he output cache allows you to bypass the round-trip server by caching data in memory. Y ou can even cache the entire page.
The OutputCache instruction is responsible for output caching. I t enables output caching and provides a degree of control over its behavior.
The syntax of the OutputCache instruction:
<%@ OutputCache Duration="15" VaryByParam="None" %>
Put this instruction under the page instruction. T his tells the environment that the page needs to be cached for 15 seconds. T he following page load event handler will help confirm that 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 processes for a specific period of time. I n this example, the thread stops for 10 seconds, so when the page is first downloaded, it takes 10 seconds. H owever, the next time you refresh the page, it won't take time because the page is already in the cache and won't download again.
The OutputCache instruction, which helps control the behavior of the output cache, has the following characteristics:
Property | Value | Describe |
---|---|---|
DiskCacheable | true/false | Describes whether the output can be written to a disk with a cache. |
NoStore | true/false | Describes whether the "no store" cache header was sent. |
CacheProfile | The name of the string | The name of the cache profile stored in web.config. |
VaryByParam |
None
* The name of the argument |
The string value separated by a sign in the GET request or the variable value in the POST request. |
VaryByHeader |
*
The header file name |
It may be a string of specified heads separated by a sign submitted by the client. |
VaryByCustom |
Browser
Custom strings |
Notify ASP.NET the output cache by browser name version or client string. |
Location |
Any
Client Download the stream Server None |
Any: The page may be cached anywhere
Client: Cached content is included in the browser Download Stream: Cached content is saved in the download stream and server Server: The cache is saved only in the server None: Cache is not allowed. |
Duration | Digital | The number of seconds the page or action was 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, the ASP caches the page by name in the text box.
The main aspect of data caching is the data source control cache. W e've discussed data source controls that represent data in a data source, such as databases or XML files. T hese controls are derived from the abstract class DataSourceControl and have the following inherited properties for caching:
To demonstrate the data cache, we create a new website with a new web form added to it. A dd a SqlDataSource control to the database that connects to the data access tutorial.
In this example, we add a label to the page that shows when the page will respond.
<asp:Label ID="lbltime" runat="server"></asp:Label>
In addition to this tag, the entire page and data access tutorial are the same. A dd an event processor 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 first execute the page, nothing different happens. T he label shows that each time the page is refreshed, the page reloads and the time changes are displayed on the label.
Next, set the EnableCaching property of the data source control to True and the Cacheduration property to 60. I t implements the cache, which expires every 60 seconds.
With each refresh, the timestamp changes. B ut if you change the data in the table within 60 seconds, it won't 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 more flexibility than other caching techniques. Y ou can use the object cache to place any object in the cache. O bjects can also be of any type - data types, network controls, classes, data setup objects, and so on. S imply assigning these items a value name allows them to be added to the cache, as shown below:
Cache["key"] = item;
To insert objects into the cache, the ASP provides the Insert() method. T here are four overloaded versions of this method. L et's take a look at:
Overload | Describe |
---|---|
Cache.Insert((key, value); | Insert the cache as a key-value pair, with priority and lifecycle as the default. |
Cache.Insert(key, value, dependencies); | Insert the cache as a key-value pair, with priority and lifecycle as the default, and cache dependencies linked to other files or content, so that cache modifications are no longer limited. |
Cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration); | Indicates the validity of the above configuration. |
Cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback); | Together with the configuration, it also allows you to prioritize and delegate cached content, indicating a way to call when an object is removed. |
Dynamic lifecycles are used to remove a cached item that does not act on any given time span. The following snipp is used to hold a dependency-free cache item with a 10-minute sliding lifecycle:
Cache.Insert("my_item", obj, null, DateTime.MaxValue, TimeSpan.FromMinutes(10));
Create a page with just one button and one label. W rite 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 in 30 seconds, the label control will get information from the cache, as follows:
Page Posted Back.
Retrieving test item.
Test item is: 14-07-2010 01:25:04