Asp.net page cache analysis

Source: Internet
Author: User
Tags data structures garbage collection microsoft sql server microsoft sql server 2005 static class server memory

Cache method
The cache in ASP. NET can be divided into two methods: Application Cache and page output cache. The former uses programming to cache data. This is the main description in this article. The latter is implemented by configuring each page or the Web. config file. There are two ways to cache the page output: one is to cache the entire page, and the other is to cache some pages ...... This part will be discussed later.

 
Auto remove
ASP. NET automatically removes data from the cache for one of the following reasons:

The server memory is too low;
The cache item expires;
The cache item dependency changes.
 
Application Cache dependency
Cache dependencies can be in the following ways: Key-value dependency; file dependency. Cache items depend on an external file, such as an XML file. If this file is modified or deleted, the cache items will be removed; SQL dependencies. The cache items depend on Microsoft SQL Server 2005, SQL Server 2000, or a table in the SQL Server 7.0 database tutorial. For SQL Server 2005, cache items can depend on a record in the table; Aggregate depends on the cache items at the same time on the frontend. For example, a cache item depends on another cache item and an external file at the same time, if one of them changes, the cache items will be removed; custom dependencies.

How to add a cache entry to a cache
You can use a Cache object in an application to access the Cache. Use the Insert method of the Cache object to add a Cache item to the Application Cache. This method has many overload methods, allowing you to add a Cache item to the Cache using different Cache policies.

If you use the Insert method to add cache items to the cache and the cache contains cache items with the same name, the cache items with the same name will be replaced (overwritten ).

You can also Add cache items to the cache using the Add method, which is the same as the Insert method. The Add method returns the object you added to the cache. In addition, if you use the Add method to Add a cache item with the same name in the cache, the cache item with the same name will not be replaced or cause exceptions.

This article describes how to add cache items to the application cache based on different cache policies:

Add a cache entry to the application cache directly by setting the key and value.
Use the Insert method to add cache items to the application cache.
Add a cache item with cache dependency to the application cache. When the cache dependency changes, this cache item will be removed from the cache. You can set cache dependencies based on other cache items, files, or multiple objects.
Add a cache entry with an expiration policy to the application cache. In addition to setting cache dependencies, you can also set the cache item to expire after a period of time (sliding expiration time) or at a specified time (absolute expiration time ), the two expiration times cannot be specified at the same time.
Add a cache entry with a cache priority to the application cache. The cache priority helps the. NET Framework determine which cache item is removed first.
Add a cache entry to the application cache using the Add method.
In addition to the preceding cache dependencies, you can create cache dependencies on database tables or customize cache dependencies. With CacheItemRemovedCallback delegation, an application is prompted when cache items are removed from the cache.

The following describes how to add a cache entry to an application:

1) add a cache item directly to the application cache by setting the key and value. The following code demonstrates how to add a cache entry with the key "CacheItem1" and value "Cached Item 1" to the cache:

Cache ["CacheItem1"] = "Cached Item 1 ";
2) add the cache items to the application cache using the Insert method. The following code demonstrates using the Insert method to add a cache entry with the key "CacheItem2" and value "Cached Item 2" to the cache:

Cache. Insert ("CacheItem2", "Cached Item 2 ");
3) add a cache item with cache dependency to the Application Cache. This cache dependency can be other cache items, files, or dependencies with multiple objects. When the cache dependency changes, this cache item will be removed from the cache. The following three examples demonstrate how to call the Insert method and pass the CacheDependency object instance to this method to add cache items to the cache.

The following code demonstrates how to use the Insert method to add a cache item with the key "CacheItem3" to the cache. This cache item depends on a cache item named "CacheItem2:

String [] dependencies = {"CacheItem2"}; Cache. Insert ("CacheItem3", "Cached Item 3", new System. Web. Caching. CacheDependency (null, dependencies ));
The following code demonstrates calling the Insert method and adding a cache item with the key "CacheItem4" to the cache. This cache item depends on the file XMLFile. xml:

Cache. Insert ("CacheItem4", "Cached Item 4", new System. Web. Caching. CacheDependency (Server. MapPath ("XMLFile. xml ")));
The following example shows how to use the Insert method to create multi-cache dependencies. A cache item depends on the cache item with the key "CacheItem1" and the file XMLFile. xml. The AggregateCacheDependency class is used here.

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 );
4) add a cache entry with an expiration policy to the application cache. In addition to setting cache dependencies, you can also set the cache item to expire after a period of time (sliding expiration time) or at a specified time (absolute expiration time ), the two expiration times cannot be specified at the same time.

The following code demonstrates the absolute expiration time of 1 minute:

Cache. Insert ("CacheItem6", "Cached Item 6", null, DateTime. Now. AddMinutes (1d), System. Web. Caching. Cache. NoSlidingExpiration );
The following code demonstrates a sliding expiration time of 10 minutes:

Cache. Insert ("CacheItem7", "Cached Item 7", null, System. Web. Caching. Cache. NoAbsoluteExpiration, new TimeSpan (0, 10, 0 ));
5) add a cache entry with a cache priority to the application cache. The cache priority helps the. NET Framework determine which cache item is removed first. The code is as follows:

Cache. insert ("CacheItem8", "Cached Item 8", null, System. web. caching. cache. noAbsoluteExpiration, System. web. caching. cache. noSlidingExpiration, System. web. caching. cacheItemPriority. high, null );
6) Add a cache entry to the application cache using the Add method. The code is as follows:

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 );
How to retrieve cache items from the cache
Specify the key value of the cache item to retrieve the data of the cache item from the cache. However, the data stored in the cache is unstable and may be stored by ASP.. NET removed. Therefore, the recommended development method is to first determine whether the cache item exists. If it does not exist, add the cache item to the cache first, and then retrieve the cache item.

The following example demonstrates how to determine whether a cache item named "CacheItem" exists. If yes, the value of the cache item is assigned to the variable cachedString; otherwise, the cache item is added to the cache, then, the value of the cache item is assigned to the variable cachedString. The code is as follows:

String cachedString; if (Cache ["CacheItem"]! = Null) {cachedString = (string) Cache ["CacheItem"];} else {Cache. insert ("CacheItem", "Hello, World. "); cachedString = (string) Cache [" CacheItem "];}
How to Remove cache in ASP. NET cache
The data in the ASP. NET cache is unstable and will not be permanently stored. It may be automatically removed from the cache for one of the following reasons:

The cache is full.
Cache entry expired
The cache dependency item has changed
In addition to the ability to automatically remove cache items, you can display the ability to remove cache items. In addition, when you use the Insert and Add methods to Add cache items to the cache, the original cache items will be automatically deleted.

Show removed cache items

Call the Remove method to pass the key value of the cache item you want to Remove to it. The following code shows how to remove a cache entry with the key value "MyData1:

Cache. Remove ("MyData1 ");
How to notify the application that the cache item has been removed
In most cache cases, when a cache item is removed, you do not need to immediately put it back into the cache unless you use it again. A typical practice is to check the cache item from the beginning. If the cached item is in the cache, use it; otherwise, the content to be cached is regenerated and added to the cache for reuse.

However, in some cases, it is very useful to notify the application that the cache items are removed. For example, if you cache a report that takes some time to generate and you want to regenerate it after the report is removed from the cache (This report is estimated to have expired, and immediately put it in the cache for the next request to use, so that the user does not need to wait. The key is that it takes time to generate the report. If you can cache the report in advance, you can directly obtain it from the cache when you need it.

ASP. NET provides CacheItemRemovedCallback to enable applications to notice that the cache item has been removed. The delegate defines an event declaration to respond to the removal of cache items from the cache. In addition, ASP. NET also provides CacheItemRemovedReason enumeration to specify the reason why the cache item is removed.

Example
The following example shows how the ReportManager class processes information after a cache item is removed. This class manages a string-type report.

Although this class uses the static modifier, it is not necessary. However, the method used to process callback must not exist. When a cache item is deleted, the method used to process the callback must exist. For example, the callback handler should not be implemented on the ASP. NET page, because the page may have been released before the item is deleted from the cache, so the method used to process the callback will be unavailable. To ensure that the method for processing callback still exists when an item is deleted from the cache, use the static class of this method. However, the disadvantage of static classes is to ensure that all static methods are thread-safe.

Note:
Do not set the CacheItemRemovedCallback to a method in a page. in addition to a page method not being available for a callback after the page is disposed, pointing the callback to a page method can prevent the memory used by the page from being reclaimed by garbage collection. this happens because the callback contains a reference to the page and the garbage collector will not remove an item from memory if the item has any references. during periods of application load, this cocould cause memory to be used up very quickly. (If you are interested, take a look at this section)

ReportManager class code


1) the private member variable "_ reportRemovedFromCache" is used to determine whether the report is removed;

2) the GetReport method obtains the report from the cache. If the report already exists, obtain it. Otherwise, create and add the report to the cache;

3) the CacheReport method is used to create and add reports to the cache.

In this common member function, the Add method of six parameters is used. The first and second parameters are the keys and values of the cache items, respectively. The third parameter is the cache dependency, in this example, there is no cache dependency, so it is null. The fourth and fifth parameters are about the expiration time, the sixth parameter is the cache priority, and the seventh parameter is the CacheItemRemovedCallback delegate, all functions with the same signature as CacheItemRemovedCallback can be used. In this example, the member function ReportRemovedCallback is used.

4) The CreateReport method is used to create a report, just a string;

5) The ReportRemovedCallback method is used to report callback. That is, re-generate the report and add the report to the cache.

Remind the application after the cache item is removed
1) create a class to retrieve cache items from the cache and process the callback method to re-add cache items to the cache.

2) in this class, create a method to add cache items to the cache.

3) create a method in this class to obtain the cache entry from the cache.

4) create a method to handle the callback of the cache item removal. This method must have the same signature as the CacheItemRemovedCallback delegate.

In this method, after a cache item is removed from the cache, for example, the cache item is regenerated and added to the cache again to complete the required logic.

Test cache item callback
1) create an ASP. NET Web page, call methods in the class, and add cache items to the cache.

The following code demonstrates that in the Page_Load event, the GetReport method in the ReportManager class is called to return the report content, which is displayed in the Lable control:

Protected void Page_Load (object sender, EventArgs e) {this. Label1.Text = ReportManager. GetReport ();}
2) request the ASP. NET page in the browser to view the report. This report will be created on the first request page, and the next request will access this report from the cache, knowing that this report has been removed.

 

Summary
Using the cache technology in ASP. NET, I personally think there are the following points:

1) the means to improve application performance can be reflected at all stages of application development, with both small details and General Directions. For example, ensure that a good software logical structure is designed; ensure that a suitable data structure is used, such as a set, a tree structure, or a linked list. All programs are composed of data structures. When talking about the data structure, it will certainly involve the basic operations of data insertion, deletion, modification, retrieval, and sorting, different data structures vary greatly in the performance of various operations. At school, I made it very clear in the data structure book, but I had no practice at the time and could not understand it. In addition, for the formal parameters of the member functions in the class, whether to use value transfer or reference transfer. When the value is passed, a copy of the parameter will be created in the called function, which will definitely consume system memory, and the reference transfer is just an address for passing the data structure ...... In short, this requires you to accumulate slowly in practice.

2) using application caching is an important way to improve application performance. It can save system resources and increase the corresponding time for users. Therefore, the cache technology is meaningful.

3) in the previous articles, you may have discovered that the cache involves only four operations: add, search (read), delete (remove), and callback. After the "add" cache item is added, you can "Retrieve (read)" it as needed. If it is not required or the cache item expires, you can "delete (remove)" it, the "callback" is to combine the above operations with application events. Reasonable. In fact, it is just the cache itself. Its operation is very simple. One statement can be completed with at most two statements. Therefore, the real question is not how to operate "add", "search", "delete", or "callback", but how to use the cache and cache, how to implement caching technology in the software logical structure is the key issue

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.