Use of ASP. NET Cache Cache

Source: Internet
Author: User
Tags set time

The ASP. NET Cache is an important way to improve system performance by using the "most recently used" principle (a least-recently-used algorithm). Caches are often used to store database data in database access .

1. Add the cache:

The addition of the cache is either add () or Insert(), and the two methods are almost similar, except that the Inser method can use the optional parameters, that is, to implement the cache additions using the default parameters:

Cache.Add (

keyname,// Cache Name

keyvalue,// the object to cache

dependencies,// Dependent Items

absoluteexpiration,// Absolute Expiration Time

slidingexpiration,// Relative Expiration Time

priority,// Priority Level

cacheitemremovedcallback);// cache expiration raises an event

2. cache dependencies:

cache can be set by the timeliness of file dependencies, other cache dependencies, database dependencies, and expiration time methods are set when the file changes, depending on the cache entry changes, when the database changes or when the time expires, the cache is invalidated, and a certain event can be raised.

2.1 file dependencies:

CacheDependency filedepends = new CacheDependency (Server.MapPath ("Northwind.xml"));
Cache.Insert ("Gridviewdataset", Dsgrid, Filedepends);
This example is used to rely on a cache using the Northiwind.xml file:
2.2 Other cache entry dependencies:
String[] Filedependsarray = {Server.MapPath ("Northwind.xml")};
String[] Cachedependsarray = {"Depend0", "Depend1", "Depend2"};
CacheDependency cachedepends = new CacheDependency (Filedependsarray, Cachedependsarray);
Cache.Insert ("Gridviewdataset", Dsgrid, Cachedepends);
This example sets the Northwind.xml file dependency and the Depend0,depend1,depend2 cache entry
Where Depend0,depend1,depend2 is an additional three caches.
If you do not need file dependencies, you can set to null.
2.3 Expiration Time Setting:
absoluteexpiration can set the absolute expiration time of the cache, such as:
Cache.Insert ("Gridviewdataset", Dsgrid, NULL, DateTime.Now.AddMinutes (+), cache.noslidingexpiration);
The cache expires 30 minutes after it is added.
noslidingexpiration can set the relative expiration time, if the cache is not accessed within the Noslidingexpiration set time, the cache expires, and if there is access during that time, the cache expiration time will be reset to the original value. such as Noslidingexpiration=20
In 20 minutes if not accessed, the cache expires, and if the cache is accessed every 19 minutes, the cache will never expire.
Cache.Insert ("Datagriddataset", Dsgrid, Null,cache.noabsoluteexpiration, Timespan.fromseconds (30));
3. Priority level:
Priority attribute value and meaning:

Priority value

Description

Notremovable

Items with this priority won't be evicted.

High

Items with this priority level is the least likely to be evicted.

AboveNormal

Items with this priority level is less likely to is evicted than items assigned Normal priority.

Default

This is equivalent to Normal.

Normal

The default value.

BelowNormal

Items with the This priority level is more likely to is evicted than items assigned Normal priority.

Low

Items with this priority level is the most likely to be evicted.

4. Cache Failure Event handling:

Using System;
Using System.Data;
Using System.Configuration;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
Using System.Web.Caching; necessary for CacheDependency
Using System.Xml; necessary for XML stuff
public partial class _default:system.web.ui.page
{
public static CacheItemRemovedCallback onremove = null;
protected void Page_Load (object sender, EventArgs e)
{
Creategridview ();
}
private void Creategridview ()
{
DataSet Dsgrid;
Dsgrid = (DataSet) cache["Gridviewdataset"];
OnRemove = new CacheItemRemovedCallback (this. RemovedCallback);
if (Dsgrid = = null)
{
Dsgrid = GetDataSet ();
String[] Filedependsarray = {Server.MapPath ("Northwind.xml")};
String[] Cachedependsarray = {"Depend0", "Depend1", "Depend2"};
CacheDependency cachedepends = new CacheDependency
(Filedependsarray, Cachedependsarray);
Cache.Insert ("Gridviewdataset", Dsgrid, Cachedepends,
DateTime.Now.AddSeconds (10),
Cache.noslidingexpiration,
Cacheitempriority.default,
OnRemove);
Lblmessage.text = "Data from XML file.";
}
Else
{
Lblmessage.text = "Data from cache.";
}
Gv. DataSource = Dsgrid.tables[0];
Gv. DataBind ();
}
Private DataSet GetDataSet ()
{
DataSet Dsdata = new DataSet ();
XmlDataDocument doc = new XmlDataDocument ();
Doc. DataSet.ReadXML (Server.MapPath ("Northwind.xml"));
Dsdata = doc. DataSet;
return dsdata;
}
public void RemovedCallback (string CacheKey,
Object CacheObject,
CacheItemRemovedReason reasontoremove)
{
WriteFile ("Cache removed for following reason:" +
Reasontoremove.tostring ());
}
private void WriteFile (string strText)
{
System.IO.StreamWriter writer = new System.IO.StreamWriter (
@ "C:" Test.txt ", true);
String str;
str = DateTime.Now.ToString () + "" + strText;
Writer. WriteLine (str);
Writer. Close ();
}
protected void Btnclear_click (object sender, EventArgs e)
{
Cache.remove ("Gridviewdataset");
Creategridview ();
}
protected void Btninit_click (object sender, EventArgs e)
{
Initialize caches to depend on.
cache["Depend0"] = "This is the first dependency.";
cache["Depend1"] = "This is the 2nd dependency.";
cache["Depend2"] = "This is the 3rd dependency.";
}
protected void Btnkey0_click (object sender, EventArgs e)
{
cache["Depend0"] = "This is a changed first dependency.";
}
}

Table 17-5. Members of the CacheItemRemovedReason enumeration

Reason

Description

Dependencychanged

A file or Item key dependency has changed.

Expired

The cached item has expired.

Removed

The cached item has been explicitly removed by the Remove method or replaced by another item with the same key.

Underused

The cached item is removed to free up system memory.

Source: http://www.cnblogs.com/leochu2008/articles/1161772.html

Use of ASP. NET Cache Cache

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.