Introduction to ASP. NET Cache Technology

Source: Internet
Author: User
Tags add time


Introduction
Cache is a technology used to store data in the memory and one of the important features provided by ASP. NET. For example, you can cache data during complex queries, so that later requests do not need to retrieve data from the database, but directly obtain data from the cache. You can use the cache to improve application performance.

There are two types of cache:

1. Output cache Output caching
2. Data caching

1. Output Caching)
With the output cache, You Can cache the final output HTML page. When the same page is requested again, ASP. NET does not execute the page lifecycle and related code, but directly uses the cached page. The syntax is as follows:

<% @ OutputCache Duration = "60" VaryByParam = "None" %>
The Duration Property setting page will be cached for 60 seconds. Any user request will be cached, and the same request will directly use the cached page within 60 seconds of the buffer. After the cache expires, ASP. NET executes the Page code again and creates a new HTML cache for the next 60 seconds.

<% @ Page Language = "C #" MasterPageFile = "~ /MasterPage. master "AutoEventWireup =" true"
CodeFile = "OutputCachingTest. aspx. cs" Inherits = "OutputCachingTest" Title = "Untitled Page" %>
<% @ OutputCache Duration = "20" 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. tow.datestring ();
LblTime. Text = DateTime. Now. ToLongTimeString ();
}

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

Cache by Query String)
In actual application, the page content is changed dynamically based on some parameters. If your page obtains information by querying strings, you can easily cache different copies of the page by querying strings. VarByParam = "None" indicates that ASP. NET only stores one copy of the cached page. VarByParam = "*" specifies that ASP. NET stores different cache pages based on different query strings.

<% @ OutputCache Duration = "60" 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 preceding example, different ID. ASP. NET in the query string stores a separate cache page for each ID. This method has some problems when querying strings in a wide range. In this case, you can specify the name of an important query string variable in the VarByParam attribute, as shown below:
<% @ OutputCacheDuration = "60" VaryByParam = "id; langid" %>

In this way, ASP. NET can cache different cache versions based on the id or langid.

Custom cache (Custom Caching)

You can also create a custom program to cache the page. ASP. NET provides a convenient way to create a custom cache. You can use the VarByCustom attribute to specify the name of the custom cache type.

% @ OutputCacheDuration = "20" VaryByParam = "None" VaryByCustom = "browser" %

You also need to create a method to generate a custom string for the cache, 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. If this method returns the same string in different requests, ASP. NET will use the cached page, otherwise a new Cache version will be generated.

In the preceding example, the GetVaryByCustomString () method creates a cache String Based on the browser name. ASP. NET creates caches of different versions based on different browser requests.

Control Cache)
The cache technology above allows you to easily cache the entire page. to cache the content of a specified control, you can specify the VaryByControl attribute.

<% @ OutputCacheDuration = "20" VaryByControl = "MyControl_1" %>

The above code ASP. NET will cache the MyControl_1 Control for 20 minutes. To Cache controls based on some attribute values, you only need to add the OutPutCache command to the *. ascx page.

<% @ Control Language = "C #" AutoEventWireup = "true" CodeFile = "MyControl. ascx. cs" Inherits = "Controls_MyControl" %>
<% @ OutputCacheDuration = "20" VaryByControl = "EmployeeID" %>
......
......

VaryByControl = "EmployeeID" tells ASP. NET to create caches of different versions based on the EmployeeID attribute declared in the control.

Add the EmplyeeID attribute to the. ascx. cs file for ASP. NET cache.

Private int_employeeID;

Public intEmployeeID
{
Get {return_employeeID ;}
Set {_ employeeID = value ;}
}

Protected voidPage_Load (objectsender, EventArgs e)
{
LblDate. Text = DateTime. Now. tow.datestring ();
LblTime. Text = DateTime. Now. ToLongTimeString ();

LblEmployeeID. Text = EmployeeID. ToString ();

}

Add a control on the page and set the employee ID.

<% @ RegisterSrc = "Controls/MyControl. ascx" TagName = "MyControl" TagPrefix = "uc1" %>
<Asp: ContentID = "Content1" ContentPlaceHolderID = "ContentPlaceHolder1" runat = "Server">
<Divalign = "center">
<Uc1: MyControlID = "MyControl1" runat = "server" EmployeeID = "1"> </uc1: MyControl>
</Div>
</Asp: Content>

Cache Profile)
Web. config allows you to configure cache-related settings,

<System. web>
<Caching>
<OutputCacheSettings>
<OutputCacheProfiles>
<Addname = "ProductItemCacheProfile" duration = "60"/>
</OutputCacheProfiles>
</OutputCacheSettings>
</Caching>
</System. web>

You can use the preceding configuration by setting the CacheProfile = "ProfileName" attribute:

% @ OutputCacheCacheProfile = "ProductItemCacheProfile" VaryByParam = "None" %

2. Data Caching)
ASP. NET also provides another flexible cache type: data cache. You can add time-consuming entries to an object cache set and store them as key values.

Cache ["Name"] = data;

You can use the Cache. Insert () method to set Cache expiration, priority, and dependencies.

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

ASP. NET allows you to set an absolute expiration time or sliding expiration time, but it cannot be used at the same time.

Cache dependency
Cache dependencies make the cache dependent on other resources. When the dependencies are changed, the cache entries are automatically removed from the cache. Cache dependencies can be files, directories, or keys with other objects in the application's Cache. If the file or directory changes, the cache will expire.

Date2 = DateTime. Now;

String [] cacheKeys = {"Date1 "};
CacheDependency cacheDepn = newCacheDependency (null, cacheKeys );
Cache. Insert ("Date2", date2, cacheDepn );

In the preceding example, the "Date2" cache object depends on the "Date1" cache entry. When the "Date1" Object expires, "Date2" will automatically expire. The first parameter in CacheDependency (null, cacheKeys) is null because we only monitor changes to the cache key.

Callback Method and Cache Priority)
ASP. NET allows us to write a callback function that is triggered when cache entries are removed from the cache. You can also set the priority of cache entries.

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 (20), 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 (40), TimeSpan. Zero,
CacheItemPriority. Default, new CacheItemRemovedCallback (CachedItemRemoveCallBack ));
}

// Set values in labels
LblDate. Text = date1.Value. tow.datestring ();
LblTime. Text = date1.Value. ToLongTimeString ();

LblDate1.Text = date2.Value. tow.datestring ();
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 ");
}
}

In this example, the "Date1" and "Date2" caches are created. "Date1" expires in 20 seconds and "Date2" is 40 seconds. However, because we have registered the removed callback function, when "Date1" or "Date2" expires, the CachedItemRemoveCallBack method will be executed. In this method, two cache entries are removed, ASP. NET also provides the callback function CacheItemUpdateCallback when processing cache entry updates.

Address: http://www.codeproject.com/KB/aspnet/AspDotNetCache.aspx

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.