Asp. NET Cache Introduction _ Basic Application

Source: Internet
Author: User
Tags date1 datetime

Asp. NET cache

Introduced

Caching is a technique for storing data in memory and one of the important features provided in asp.net. For example, you can cache data in complex queries so that subsequent requests do not need to retrieve data from the database, but are retrieved directly from the cache. By using caching, you can improve the performance of your application.

There are two main types of caching:

Output Cache caching\

Data cache Caching

1. Output cache (Caching)

With output caching, you can cache the final output of the HTML page, and when the same page requests again, the ASP. NET does not execute the page life cycle and related code, but uses the cached page directly, the syntax is as follows:

Copy Code code as follows:

<%@ OutputCache duration= "No" varybyparam= "None"%>

Duration Property Settings page will be cached 60 wonderful. Any user request is cached, and the same request will be used directly in the cached page for 60 seconds of Buffering. When the cache expires, ASP.net executes the page code again and creates a new HTML cache for the next 60 seconds.
Copy Code code as follows:

<%@ Page language= "C #" masterpagefile= "~/masterpage.master" autoeventwireup= "true" codefile= " OutputCachingTest.aspx.cs "inherits=" Outputcachingtest "title=" Page "%>
<%@ OutputCache duration= "No" varybyparam= "None"%>
<asp:content id= "Content1" contentplaceholderid= "ContentPlaceHolder1" runat= "Server" >
<div class= "title" >output cache</div>
Date: <asp:label id= "lbldate" runat= "Server" text= ""/>
Time: <asp:label id= "Lbltime" runat= "Server" text= ""/>
</asp:Content>
protected void Page_Load (object sender, EventArgs e)
{
Lbldate.text = DateTime.Now.ToShortDateString ();
Lbltime.text = DateTime.Now.ToLongTimeString ();
}


In this example, the page will be cached for 20 seconds.

caching via query string (cache by query strings)

In the actual application of the page will often be based on a number of parameters dynamically change the content of the page. If your page is using a query string to get information, you can easily cache different copies of the page based on the query string. Varbyparam= "None" specifies that asp.net stores only one copy of the cached page. Varbyparam= "*" specifies that asp.net store different cached pages based on different query strings.
Copy Code code as follows:

<%@ OutputCache duration= "*" varybyparam= "*"%>
<div align= "Right" >
<a href= "outputcachingtest2.aspx" >no Query string</a> |
<a href= "outputcachingtest2.aspx?id=1" >id 1</a> |
<a href= "outputcachingtest2.aspx?id=2" >id 2</a> |
<a href= "outputcachingtest2.aspx?id=3" >id 3</a> |
<a href= "outputcachingtest2.aspx?id=3&langid=1" >id 3</a>
</div>

In the example above, a separate cache page is stored for each ID in a different ID.ASP.NET in the query string. There are some problems with this approach when the query string is wide range.
This time we can specify the name of an important query string variable in the Varbyparam attribute, as follows:
Copy Code code as follows:

% @OutputCacheDuration = "Id;langid" varybyparam= "%"

customizing caching (Custom Caching)
You can also create custom programs to cache pages. Asp. NET provides a convenient way to create a custom cache, using the Varbycustom property to specify the name of the custom cache type.
You also create a method for generating custom strings for caching, as follows:
Copy Code code as follows:

public override Stringgetvarybycustomstring (HttpContext context, Stringcustom)
{
if (custom = "Browser")
{
Returncontext. Request.Browser.Browser +
Context. Request.Browser.MajorVersion;
}
Else
{
Return base. GetVaryByCustomString (context, custom);
}
}


This method must be written in the Global.asax file. Asp. NET uses the string returned by this method to implement caching if the method returns the same string in different requests, the ASP. NET will use cached pages, or a new cached version will be generated.
In the example above, the GetVaryByCustomString () method creates a cached string based on the name of the browser, ASP. NET creates different versions of the cache based on different browser requests.
Controls caching (control cache)
The above caching technology allows you to easily cache the entire page, and if you want to cache the contents of the specified control, you can do so by specifying the VaryByControl property.
Copy Code code as follows:

% @OutputCacheDuration = "mycontrol_1" varybycontrol= "%"

The code asp.net above will cache the Mycontrol_1 control for 20 minutes. If you want to cache a control based on some property values, just add the outputcache instruction to the *.ascx page.
Copy Code code as follows:

<% @Control language= "C #" autoeventwireup= "true" codefile= "MyControl.ascx.cs"
inherits= "Controls_mycontrol"%>
<% @OutputCacheDuration = "varybycontrol=" "EmployeeID"%>

Varybycontrol= "EmployeeID" tells ASP.net to create different versions of the cache based on the EmployeeID properties declared in the control.
The Emplyeeid property is added to the asp.net cache in the. ascx.cs file.
Add controls to the page and set EmployeeID.
Copy Code code as follows:

Private Int_employeeid;
Public Intemployeeid
{
get{Return_employeeid;}
set{_employeeid = value;}
}
Protected Voidpage_load (Objectsender, EventArgs e)
{
Lbldate.text = DateTime.Now.ToShortDateString ();
Lbltime.text = DateTime.Now.ToLongTimeString ();
Lblemployeeid.text = Employeeid.tostring ();
}

Cached profiles (Cache profile)
Web.config can configure cache-related settings.
Copy Code code as follows:

<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<addname= "Productitemcacheprofile" duration= "/>"
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>

You can use the above configuration by setting the cacheprofile= "ProfileName" attribute:
Copy Code code as follows:

% @OutputCacheCacheProfile = "Productitemcacheprofile" varybyparam= "None"%

2. Data caching (Caching)
Asp. NET also provides another flexible type of caching: Data caching. You can add some time-consuming entries to an object cache collection and store them as key values.
Copy Code code as follows:

cache["Name" = data;


We can set the cache expiration, priority, dependencies, and so on by using the Cache.Insert () method.
Copy Code code as follows:

Date1 = DateTime.Now; Cache.Insert ("Date1", date1, NULL, DateTime.Now.AddSeconds (), TimeSpan.Zero);


Asp. NET allows you to set an absolute expiration time or sliding expiration time, but not at the same time.
Cached Dependencies Cache dependency
Cache dependencies make caching dependent on other resources, and when a dependency changes, the cached entry items are automatically removed from the cache. A cache dependency can be a file, a directory, or a key to another object in the cache of an application. If a file or directory changes, the cache expires.
Copy Code code as follows:

Date2 = DateTime.Now;
String[] Cachekeys = {"Date1"};
CacheDependency CACHEDEPN = newcachedependency (null, cachekeys);
Cache.Insert ("Date2", Date2, CACHEDEPN);


The above example "Date2" cache object relies on the "Date1" cache entry, and "Date2" expires automatically when the "Date1" object expires. The first argument in CacheDependency (null, cachekeys) is NULL because we only monitor changes to the cache key.
Callback functions and cache precedence (Callback method and cached Priority)
Asp. NET allows us to write a callback function that fires when the cache entry is removed from the cache. You can also set the priority of the cache entry.
Copy Code code as follows:

protected void Page_Load (object sender, EventArgs e)
{
Datetime? Date1 = (DateTime?) cache["Date1"];
if (!date1. HasValue)//date1 = NULL
{
Date1 = DateTime.Now;
Cache.Insert ("Date1", date1, NULL, DateTime.Now.AddSeconds (), TimeSpan.Zero,
Cacheitempriority.default, New CacheItemRemovedCallback (Cacheditemremovecallback));
}
Datetime? Date2 = (DateTime?) cache["Date2"];
if (!date2. HasValue)//Date2 = NULL
{
Date2 = DateTime.Now;
Cache.Insert ("Date2", date2, NULL, DateTime.Now.AddSeconds (), TimeSpan.Zero,
Cacheitempriority.default, New CacheItemRemovedCallback (Cacheditemremovecallback));
}
Set Values in labels
Lbldate.text = Date1. Value.toshortdatestring ();
Lbltime.text = Date1. Value.tolongtimestring ();
Lbldate1.text = Date2. Value.toshortdatestring ();
Lbltime1.text = Date2. Value.tolongtimestring ();
}
private void Cacheditemremovecallback (string key, object value, CacheItemRemovedReason reason)
{
if (key = = "Date1" | | | key = = "Date2")
{
Cache.remove ("Date1");
Cache.remove ("Date2");
}
}


The "Date1" and "Date2" caches are created in the example. "Date1" expires in 20 seconds after "Date2" is 40 seconds. However, since we registered the removed callback function, when "Date1" or "Date2" one of the expiration will execute the Cacheditemremovecallback method, in this method removed two cache entries, ASP. NET also provides a callback function cacheitemupdatecallback when processing cache entry updates.
Original: http://kb.cnblogs.com/page/50971/

Related Article

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.