System.Web.Caching.Cache

Source: Internet
Author: User
Tags httpcontext

This class uses caching to hold information. You can optimize the speed of your site by storing data that is stable and that does not change with the user, using the cache.

The difference between cache and Session,cookie

Session is saved on the server, each user has its own session, will not conflict, the session is lost after closing the site.

Cookies are stored on the client, and cookies are not lost if you do not clear the cookie for the rover or if you do not set the expiration time.

The cache is a common memory slice that is allocated on the server. Reading data from the cache is faster, and some websites put some of the data that is often used in the cache, improving access speed and optimizing system performance.

Here is the main introduction of the cache three methods. Insert (), get (), remove () is add, get, delete

Insert has overloaded

//page.cache and HttpContext.Current.Cache and general handler context. The Cache is not the same, you use what to save what to take//Insert and get processes if boxing and unpacking are the same        protected Override voidOnInit (EventArgs e) {//Add the cache,//you think of the parameter as a key-value pair, just that the type of the key is OK (you can repeat, you can set the key next time), and the value can be any typePage.Cache.Insert (" One","666");//as long as it is saved, it can be retrieved from the following pages        }        protected voidPage_Load (Objectsender, EventArgs e) {                       stringAA =""; if(Page.Cache.Get (" One") !=NULL)//before using the final judgment, in order to avoid the project error{AA=(string) Page.Cache.Get (" One");//get the time needed to transform} Response.Write (AA+"<br/>"); if(Page.Cache.Get ("Ywo") ==NULL)//no this key is empty{Response.Write ("no this value <br/>"); }                }

This method is capable of monitoring a file, and if the monitored file has changed, the cache is cleared.

For example:

① Create a new XML-formatted file to hold the information, and then do the following preparatory work

Create a new class to make a comparison

Using code to generate an XML file, run it once and annotate it, and replace it with the following.

    protected Override voidOnInit (EventArgs e) {TestClass xiaoming=NewTestClass () {ID =1, age = -, Name ="Xiao Ming" }; XmlSerializer XML=NewXmlSerializer (xiaoming.            GetType ()); stringPath = Server.MapPath ("~/xm.xml"); using(Stream stream =NewFileStream (Path, FileMode.Create, FileAccess.Write, Fileshare.readwrite)) {XML.            Serialize (stream, xiaoming); } cachedependency CDD=Newcachedependency (path); HttpContext.Current.Cache.Insert ("XM", Xiaoming, CDD);
//This code can be deleted once it is run, the code is replaced by the following
}
 protected Override voidOnInit (EventArgs e) {//ReadXmlSerializer XML =NewXmlSerializer (typeof(TestClass)); TestClass xiaoming=NewTestClass (); stringPath = Server.MapPath ("~/xm.xml"); using(Stream stream =NewFileStream (Path, FileMode.Open, FileAccess.Read, Fileshare.readwrite)) {Xiaoming=(TestClass) XML.            Deserialize (stream); } cachedependency CDD=Newcachedependency (path); HttpContext.Current.Cache.Insert ("XM", Xiaoming, CDD); }

Then generate the XML file as follows

Our page structure

The button is to modify our XML file, click the button, we saved the cache is also cleared

         Public voidProcessRequest (HttpContext context) {
This general processing handler is used to display the effect
Context. Response.ContentType="Text/plain"; TestClass XM=NULL; if(Context. Cache.get ("XM") !=NULL) {XM=httpcontext.current.cache.get ("XM") asTestClass; } MemoryStream Ms=NewMemoryStream (); XmlWriter XW=NewXmlTextWriter (MS,NULL); Xw. WriteStartDocument (); Xw. WriteStartElement ("XM"); Xw. WriteElementString ("ID", Xm.id. ToString ()); Xw. WriteElementString ("Name", XM. Name); Xw. WriteElementString (" Age", XM. Age.tostring ()); Xw. WriteEndElement (); Xw. Flush (); Ms. Flush (); //change the flow to a string and return byte[] data =New byte[Ms. Length]; Ms. Seek (0, Seekorigin.begin); Ms. Read (data,0, data. Length); Ms. Close (); stringAA =UTF8Encoding.UTF8.GetString (data); Context. Response.ContentType="Text/xml"; Context. Response.Write (AA); }

② Open our page

The principle is: when we open our page, we will put the information inside the xm.xml into the cache, we click on the a tag will see the effect, and then we click the button (the purpose is to change the Xm.xml file), Then clicking on the a tag will cause an error .

The effect is as follows:

Then click on the button, and then look at the a tag will error, proof that our cache has been cleared.

There are two fields in the Cahe, and the DateTime is returned.

For example: two forms of

This method manually sets the cache expiration

Note: The difference between ADD () and insert ()

Both add () and insert () can represent the addition of a buffer, and add () sets the value of the key that cannot be changed, as is the constant. Insert () can change the value of key. Therefore, it is generally recommended to use the Insert () method

System.Web.Caching.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.