Reproduced http://www.cnblogs.com/leochu2008/articles/1161772.html
ASP. NET CacheIs an important way to improve system performance, it uses the "recently used" principle (A least-recently-used algorithm). Frequently Used in Database AccessCacheSave database data.
1.Add cache:
CacheMethods to addAdd ()OrInsert(), The two methods are almost similar,InserYou can use the optional parameter (default parameter) to add a cache:
Cache. Add (
Keyname ,//Cache name
KeyValue ,//Object To be cached
Dependencies ,//Dependency
Absoluteexpiration ,//Absolute expiration time
Slidingexpiration ,//Relative expiration time
Priority ,//Priority
Cacheitemremovedcallback );//Events caused by cache expiration
2.Cache dependencies:
The cache can be set in a timely manner through File dependencies, other cache dependencies, database dependencies, and expiration time methods are set. When the file changes, the dependent cache items change, the database changes, or the expiration time, the cache will become invalid, and can cause certain events.
2.1File dependency:
Cachedependency filedepends = new cachedependency (server. mappath ("northwind. xml "));
Cache. insert ("gridviewdataset", dsgrid, filedepends );
In this example, the cache is dependent on the northiwind. xml file:
2.2 Other cache item dependencies:
String [] filedependsarray = {server. mappath ("northwind. xml ")};
String [] cachedependsarray = {"depend0", "depend1", "depend2 "};
Cachedependency cachedepends = new cachedependency (filedependsarray, cachedependsarray );
Cache. insert ("gridviewdataset", dsgrid, cachedepends );
In this example, the northwind. xml file dependency and depend0, depend1, and depend2 cache items are set.
Depend0, depend1, and depend2 are the other three caches.
If no file dependency is required, you can set it to null.
2.3 expiration time setting:
AbsoluteexpirationYou can set the absolute cache expiration time, for example:
Cache. insert ("gridviewdataset", dsgrid, null, datetime. Now. addminutes (30), cache. noslidingexpiration );
The cache will expire 30 minutes after it is added.
NoslidingexpirationYou can set the relative expiration time. If the cache is not accessed within the time set by noslidingexpiration, the cache expires. If there is access within this time period, the cache expiration time is reset to the original value, for example, noslidingexpiration = 20
The cache expires if it is not accessed within 20 minutes. If it is accessed for 19 minutes each time, the cache will never expire.
Cache. insert ("maid", dsgrid, null, cache. noabsoluteexpiration, timespan. fromseconds (30 ));
3. Priority:
Priority attribute value and meaning:
priority value |
description |
notremovable |
items with this priority will not be evicted. |
high |
items with this priority level are the least likely to be evicted. |
abovenormal |
items with this priority level are less likely to be evicted than items assigned normal priority. |
default |
This is equivalent to normal. |
normal |
the default value. |
belownormal |
items with this priority level are more likely to be evicted than items assigned normal priority. |
Low |
Items with this priority level are the most likely to be evicted. |
4.Handle cache invalidation events:
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 was removed to free up system memory. |