ASP. NET provides a powerful and easy-to-use cache mechanism for you to store objects that require a large number of server resources in the memory. Caching these types of resources will greatly improve the applicationProgramPerformance.
The cache is implemented by the cache class, And the cache instance is dedicated to each application. The cache lifetime depends on the lifetime of the application. After the application is restarted, the cache object is created again.
The cache class is designed for ease of use. You can place items in the cache and use simple key/value pairs to retrieve these items in the future.
The cache class provides powerful functions that allow you to customize how to cache items and how long they will be cached. For example, in the absence of system memory, the cache automatically removes rarely used or lower-priority items to release the memory. This technology, also known as cleanup, is one of the ways in which the cache ensures that expired data does not use valuable server resources.
When cleaning, you can instruct the cache to give some items a higher priority than others. To indicate the importance of an item, you can specify a cacheitempriority enumeration value when adding an item using the Add or insert method.
When you add an item to the cache using the Add or insert method, you can also create an expiration Policy for the item. You can use the datetime value to specify the exact expiration time (absolute expiration time) of an item to define the lifetime of the item. You can also use the timespan value to specify an elastic expiration time. The elastic expiration time allows you to specify the running time before the item expires Based on the item's last access time. Once an item expires, it is removed from the cache. The attempt to retrieve its value will return NULL (nothing in Visual Basic) unless it is re-added to the cache.
For the loss-prone items stored in the cache (for example, items that regularly rerefresh data or those that valid only for a period of time), an expiration Policy is usually set: as long as the data of these items is kept up-to-date, they are kept in the cache. For example, if you are writing an application that obtains data from another website to track the score of a sports match, as long as the score of the game on the source website is not changed, you can cache these scores. In this case, you can set an expiration policy based on the frequency of score updates on other websites. You can writeCodeTo determine whether the cache is the latest score. If the score is not latest, the code can read the score from the source website and cache the new value.
Finally, ASP. NET allows you to define the validity of cache items based on external files, directories (File dependencies), or another cache item (key dependencies. If the items with associated dependencies are changed, the cache items are invalid and removed from the cache. You can use this technology to remove items from the cache when their data sources change. For example, if you write an application that processes financial data in an XML file, you can insert data into the cache from this file and keep a dependency on this XML file. When the file is updated, this item is removed from the cache, your application reads the XML file again, and then refresh the data into the cache.
Add items to cache
You can use the cache object to access the items in the application cache. You can use the insert method of the cache object to add items to the application cache. This method adds items to the cache, and you can use different options to add items through several reloads to set dependencies, expiration, and removal notifications. If you use the insert method to add items to the cache and an item with the same name as the existing item already exists, the existing items in the cache will be replaced.
You can also use the add method to add items to the cache. With this method, you can set all options identical to the insert method. However, the add method returns the object you added to the cache. In addition, if the add method is used and an item with the same name as an existing item already exists in the cache, this method will not replace this item and will not cause an exception.
Add items to the cache using keys and values.
By specifying the key and value of an item, add it to the cache just like adding the item to the dictionary.
The following code example adds an item named cacheitem1 to the cache object:
Cache ["cacheitem1"] = "cached Item 1 ";
Add items to the cache by using the insert method
Call the insert method to pass the key and value of the item to be added.
The following code example adds a string named cacheitem2:
Cache. insert ("cacheitem2", "cached Item 2 ");
Add items to the cache by specifying Dependencies
Call the insert method to pass an instance of the cachedependency object to this method.
The following code example adds an item named cacheitem3, which depends on another item named cacheitem2 in the cache:
String [] dependencies = {"cacheitem2 "};
Cache. insert ("cacheitem3", "cached Item 3 ",
New system. Web. caching. cachedependency (null, dependencies ));
The following code example shows how to add an item named cacheitem4 to the cache and set a file dependency on a file named xmlfile. xml:
Cache. insert ("cacheitem4", "cached Item 4 ",
New system. Web. caching. cachedependency (
Server. mappath ("xmlfile. xml ")));
The following code example shows how to create multiple dependencies. It adds a key dependency to another item in the cache named cacheitem1, and adds a file dependency to a file named xmlfile. xml.
System. Web. caching. cachedependency dep1 =
New system. Web. caching. cachedependency (server. mappath ("xmlfile. xml "));
String [] keydependencies2 = {"cacheitem1 "};
System. Web. caching. cachedependency dep2 =
New system. Web. caching. cachedependency (null, keydependencies2 );
System. Web. caching. aggregatecachedependency aggdep =
New system. Web. caching. aggregatecachedependency ();
Aggdep. Add (dep1 );
Aggdep. Add (dep2 );
Cache. insert ("cacheitem5", "cached Item 5", aggdep );
Add an item with an expiration Policy to the cache
Call the insert method to pass the absolute or elastic expiration time to the method.
The following code example adds an item with an absolute expiration time of one minute to the cache:
Cache. insert ("cacheitem6", "cached Item 6 ",
Null, datetime. Now. addminutes (1D ),
System. Web. caching. cache. noslidingexpiration );
The following code example adds an item with an elastic expiration time of 10 minutes to the cache:
Cache. insert ("cacheitem7", "cached Item 7 ",
Null, system. Web. caching. cache. noabsoluteexpiration,
New timespan (0, 10, 0 ));
Add items with priority settings to the cache
Call the insert method to specify a value from the cacheitempriority enumeration.
The following code example adds an item with a high priority to the cache:
Cache. insert ("cacheitem8", "cached Item 8 ",
Null, system. Web. caching. cache. noabsoluteexpiration,
System. Web. caching. cache. noslidingexpiration,
System. Web. caching. cacheitempriority. High, null );
Use the add method to add items to the cache
Call the add method to return an object that represents the item.
The following code example adds an item named cacheitem9 to the cache and sets the value of the variable cacheditem9 to an added item.
String cacheditem9 = (string) cache. Add ("cacheitem9 ",
"Cached Item 9", null,
System. Web. caching. cache. noabsoluteexpiration,
System. Web. caching. cache. noslidingexpiration,
System. Web. caching. cacheitempriority. Default,
Null );
Cache dependency example:
Create a button on the page to check whether the cache exists.
When the form is started, we create a cache with the name = "txt2" and the value = dataset Ds.
This cache is associated with myfile. xml. When the myfile. xml file changes, txt2cache is automatically deleted.
Private void page_load (Object sender, system. eventargs E)
{
If (! Ispostback)
{
String filepath = mappath ("myfile. xml ");
Sqlconnection con = new sqlconnection ("uid = sa; database = pubs ;");
Sqldataadapter da = new sqldataadapter ("select * from authors", con );
Dataset DS = new dataset ();
Da. Fill (DS );
System. Web. caching. cachedependency cachedependencyxmlfile = new system. Web. caching. cachedependency (filepath );
Cache. insert ("txt2", DS, cachedependencyxmlfile );
}
}
To monitor changes in the authors table of the pubs Database
You can create a trigger in the authors table of the pubs database.
Once the authors table is added or deleted, the trigger automatically modifies the file myfile. xml.
Once the myfile. xml file changes, txt2cache is automatically deleted by the system.
Create trigger tr_authors
On authors
For insert, update, delete
As
Declare @ cmd nvarchar (4000)
Select @ cmd = 'bcp "select convert (nvarchar (30), getdate (), 13)" queryout D: \ cache \ webcache \ myfile. XML-C-sglc2403-USA-p'
Exec master .. xp_mongoshell @ cmd
Go
Private void querybutton_click (Object sender, system. eventargs E)
{
If (Cache ["txt2"]! = NULL)
{
Response. Write ("exists ");
}
Else
{
Response. Write ("not exists ");
}
}
First, click the button to display that cache ["txt2"] exists.
Now we can modify any data in the table authors and click the button to show that cache ["txt2"] does not exist.
We associate the cache with a file. We can also associate the cache with a file group to establish dependencies.
In the following example, we associate the cache with two files (myfile. XML, myfile1.xml). Once any file in the file group changes, the cache will delete the data of the "txt2" item from the cache.
String [] filepath = new string [] {mappath ("myfile. xml"), mappath ("myfile1.xml ")};
System. Web. caching. cachedependency cachedependencyxmlfile = new system. Web. caching. cachedependency (filepath );
String cachevaule = "";
Cache. insert ("txt2", cachevaule, cachedependencyxmlfile );
Cache dependencies can be files or keys of other objects
The following code indicates that cache ["txt2"] depends on the file myfile. the cache ["TXT"] in the cache is also dependent on XML. As long as the two are changed in the same way, the cache ["txt2"] will be cleared.
Cache ["TXT"] = "B ";
String [] filepath = new string [] {mappath ("myfile. xml ")};
String [] dependencykey = new string [] {"TXT "};
Sqlconnection con = new sqlconnection ("uid = sa; database = pubs ;");
Sqldataadapter da = new sqldataadapter ("select * from authors", con );
Dataset DS = new dataset ();
Da. Fill (DS );
System. Web. caching. cachedependency cachedependencyxmlfile =
New system. Web. caching. cachedependency (filepath, dependencykey );
Cache. insert ("txt2", DS, cachedependencyxmlfile );
Retrieve the value of a cache item
To retrieve data from the cache, specify the key to store the cache item. However, because the information stored in the cache is easy to lose, that is, the information may be removed from ASP. NET, we recommend that you first determine whether the information is cached. If not, add it to the cache again and then retrieve the item.
Check the cache object to determine whether the item is not null (nothing in Visual Basic ). If this option exists, assign it to the variable. Otherwise, re-create the item, add it to the cache, and then access it.
The following code example shows how to determine whether an item named cacheitem is included in the cache. If yes, the code will allocate the content of the item to the variable named cachedstring. If this item is not in the cache, the Code adds it to the cache and assigns it to cachedstring.
String cachedstring;
If (Cache ["cacheitem"]! = NULL)
{
Cachedstring = (string) cache ["cacheitem"];
}
Else
{
Cache. insert ("cacheitem", "Hello, world .");
Cachedstring = (string) cache ["cacheitem"];
}
Delete items from ASP. NET Cache
Data in the ASP. NET cache is easy to lose, that is, it cannot be stored permanently. Data in the cache may be automatically removed for any of the following reasons:
1. the cache is full.
2. This item has expired.
3. The dependency is changed.
Explicitly delete an item from the cache
Call the Remove Method to pass the key of the item to be removed.
The following example shows how to remove an entry whose key is mydata1.
Cache. Remove ("mydata1 ");
Notification application when items are removed from the cache
In most cache schemes, items need to be removed from the cache until they are required again. A typical development mode is to always check whether the item is in the cache before you use it. If the item is in the cache, it can be used. If it is not in the cache, you should retrieve the item again and add it back to the cache.
However, in some cases, it may be useful to notify the application when items are removed from the cache. For example, you may have a cached report, which takes a lot of time to process. When the report is removed from the cache, you want to regenerate the report and place it in the cache so that you do not have to wait for the report to be processed the next time you request the report.
ASP. NET provides the cacheitemremovedcallback delegate to send notifications when items are removed from the cache. This delegate defines the signature used to write an event handler. When an item is removed from the cache, this event handler is called. ASP. NET also provides cacheitemremovedreason enumeration to specify the reason for removing cache items.
Generally, callback is implemented by creating a processing program in the business object that manages the specific cache data to be retrieved. For example, you may have a reportmanager object, which has two methods: getreport and cachereport. The getreport report method checks the cache to check whether the report has been cached. If not, this method re-generates the report and caches it. The cachereport method has the same function signature as the cacheitemremovedcallback delegate. When a report is removed from the cache, ASP. NET calls the cachereport method and adds the Report to the cache again.
Notification application when items are removed from the cache
1. Create a class to retrieve items from the cache and process the callback method to add the items back to the cache.
2. In this class, create a method to add an item to the cache.
3. In this class, create a method to obtain items from the cache.
4. Create a method for processing the callback for removing cache items. This method must have the same function signature as the cacheitemremovedcallback delegate. When an item is deleted from the cache, the logic to be run is executed in this method, such as re-generating the item and adding it back to the cache.
Static system. Web. caching. cacheitemremovedreason reason;
System. Web. caching. cacheitemremovedcallback onremove = NULL;
Public void removedcallback (string K, object v, system. Web. caching. cacheitemremovedreason R)
{
Itemremoved = true;
Reason = R;
}
Onremove = new system. Web. caching. cacheitemremovedcallback (this. removedcallback );
Cache. insert ("TXT", DS, null,
System. Web. caching. cache. noabsoluteexpiration,
System. Web. caching. cache. noslidingexpiration,
System. Web. caching. cacheitempriority. Default, onremove );
The removedcallback method will be called when the cache is removed for any reason
Http://aierong.cnblogs.com
SQL server2005 Transact-SQL new weapon learning Summary-Summary
Ms SQL database backup and recovery stored procedures (enhanced)
SQL Server Distributed Query essay (sp_addmediaserver) and remote login ing (sp_addmediasrvlogin) use small summary)
WAP development data station (latest update)
Custom Format String (implementation of the three interfaces of iformattable, iformatprovider, and icustomformatter)
Asynchronous programming of mcad learning notes (asynccallback delegation, iasyncresult interface, begininvoke method, and endinvoke method)
Mcad learning notes: Calling class methods through reflection, attention, fields, indexers (2 methods)
Serialization of mcad learning notes (binary and soap serialization)
Delegated re-understanding of mcad learning notes (discussion of Delegate constructor, begininvoke, endinvoke, and invoke4 methods)
Winform development, form display, and form value passing knowledge
Microsoft Windows service using mcad Study Notes
Copy all the objects and files under a certain category to the target category (number of objects)
ASP. NET status management (Summary)