Introduction to ASP. NET Cache Usage

Source: Internet
Author: User
Tags set time


When I explain the cache management mechanism, let me first clarify the next idea: the data management under IE. Everyone will use different methods to solve how to manage data in IE. Some will refer to the use of state management, some mention of the cache management, here I prefer the cache management, because I am more happy "cache" the word. But state management and cache management are different in concept and in meaning, so let's talk about the differences between the two in each area.

Although cache management does not exist in Windows programs, it has already been used in a Web environment. Since HTTP became a non-protocol, it is very difficult to distinguish two different requests on the web, it is important to distinguish so many requests, and if it is the same request, we can cache the data for access by all users on the web and reduce the physical loading of data duplication.

ASP. NET provides several ways to cache data on both the client and server side, but we often get annoyed by the way in which it is used. ASP. NET provides the following three implementations:

1:session;2:application 3:cache objects, we have to be very clear about the advantages between them so that we can take full advantage of their advantages in the Web program.


In this article, I will simply cover the different functions in the cache management, in the Web program, in order to avoid the high concurrency caused by the data access performance problems, we need to cache the data on the server side, so that later access can directly invoke the cache data, play the role of data reuse.

Caching helps us to mention three important aspects of quality of service:

Performance: cache data for data reuse. Avoids duplicate physical data loading.

measurable: after data cache, the data is reduced from server-side loading.

practicality: If the other system or the database crashes, then the data can still be obtained from the cache is not affected by the local hardware.

In a Web program, we can cache data, page cache, and so on, let's look at the difference between the data cache on the server side and the client.

1. Server-Side Caching:

1.1. Session state management:

Session for each person to cache data, facing a single user , namely: themselves. This means that the cached data cannot be shared by multiple people at the same time , and is limited to caching data for a single person .

There are three ways to implement state management, namely:


Its data is stored in the Aspnet_wp.exe process, and the data is lost because of the IIS restart.


Unlike InProc, it can be stored on different servers.


Its data is stored in the database, and data is not lost because of IIS restarts.

The biggest difference between the latter two methods and the InProc is that we want to make sure that the cached data is serializable, otherwise it can only be used in the first way. For this we have to carefully analyze and choose the best way for ourselves.

Here is a snippet of how the session works:

String empnum = request.querystring["Empnum"];if (empnum! = null) {    string details = null;    if (session["emp_details"] = = null)    {        string DETAILS = Getemployeedetails (Convert.ToInt32 (Empnum));        session["emp_details"] = DETAILS;     }    else    {        details = session["Emp_details"];     }    Send it to the browser    Response.Write (details);}

1.2 ASP. Application
ASP. NET provides us with another way to save global variables, the Application object, which is also a polygon to all users , whose lifecycle is also dependent on the application, and it starts rebuilding when the application is initialized. But its biggest disadvantage is:application can not specify the expiration time, only by manually using the Remove or RemoveAll or RemoveAt method or close the application to remove, to achieve expiration, so not too smart ,the cache management will be used at this time.

1.3 asp . NET Cache

The cache is for all users , and the difference between application: The cache can be expired based on the set time, not remove
The cache is my favorite mechanism, which is why I like to say it. It provides a method for the key-value correspondence,

The namespace for the cache is: System.Web.Caching its lifecycle is also dependent on the application, and it starts rebuilding when the application is initialized, but it is not like a session, which is for all users.

Although the cache looks particularly like application, the biggest difference is that it provides a data cache failure control method (thecache can specify an expiration time ) and data cache dependency Management . That is, in the cache we can very easily follow the pre-set expiration time to let the cache expire , delete the cache, we can also be based on cache dependencies to operate the cache, when the dependent relationship changes, the cache will automatically expire. And that's all applicaion can't do.

Now let's look at how the cache expiration and data cache dependencies are supported in ASP.

1.31: Cache dependency:

As the name implies, it means that the cache will expire when a predetermined dependency is changed . Two types of dependencies are available in asp:
1.311: File Cache dependent : Automatically invalidates the cache when a file on disk changes
Here is the instance code:

String Errordata= "Cached content";   Load errordata from Errors.xml cachedependency filedependency =new cachedependency (Server.MapPath ("Errors.xml")); Cache.Insert ("Error_info", ErrorData, filedependency);

1.312: Key-Value Cache Dependent : It looks like a file cache, except that this dependency is different, and when there are multiple cache information associated with each other, a change in the cache information will cause the other cache to fail. For example, a user information includes: number, name, address, etc., if the user number changes, the cache fails, in this case, the user's basic information depends on the user number.
Here is the sample code:

when Emp_num is modified or does not exist, the dependent cache is emptied

1.32: Expiration Policy: automatically expires after a period of time, starting with the creation of the cache.
Example code:

Absolute Cache Cache.Insert ("Emp_name", "Shubhabrata", Null, (1), cache.noslidingexpiration);// Slide Cache Cache.Insert ("Emp_name", "Shubhabrata", Null,cache.noabsoluteexpiration, Timespan.fromseconds (60));

1.4 ASP. NET page Output cache

Sometimes in the Web site, some pages in a long period of time will not change, such as a recruitment site, it is the salary of the descriptive text is generally not changed frequently, usually one months change, so in this one months, the user sees the same content , All if the data is cached on the server side is not the perfect solution. Here you can use the page output cache.

OutputCache parameter Description:

Here is the sample code:
<% @OutputCache duration= "" varybyparam= "Empnum" location= "Server"%>

2: Client cache [mainly introduces cookies, ViewState, Hidden]:

In the previous article, I discussed some of the ways that data is cached on the server side, but sometimes we want to cache some data to the client in order to improve performance. Using this mechanism to alleviate the server pressure, but the client cache data will have a variety of security issues, the following I said briefly the relevant content:

2.1 Cookies:cookies are widely used in Web application development, it is very convenient to access the client and server side, but it has the data size limit, the maximum is 4K, all used it is often to save small data. At the same time, cookie support for the failure of the control is quite perfect.

Here is the sample code:

if (this. request.cookies["My_name"] = = null) {This    . RESPONSE.COOKIES.ADD (New HttpCookie ("My_name", "Shubhabrata Mohanty")); else{this    . Response.Write (this. request.cookies["My_name"]. Value);}

2.2 ViewState: ViewState is a brand new concept that is typically used for pages or controls that retain data for service-side traffic. In ASP, we store data with a hidden control (Hidden fields), ViewState is also used, but it is more secure than the hidden control, all the values are hashed. If you look at the page source code, you will see the existence of ViewState, general ViewState do not need to save large data.

Here is the sample code:

protected void Page_Load (object sender, EventArgs e) {    if (this. viewstate["My_name"] = = null)    {this        . viewstate["my_name"] = "Shubhabrata Mohanty";    }        Txtname is a TextBox control    This.txtName.Text = this. viewstate["My_name"]. ToString ();}

2.3 Hidden Controls Hiddenfields: It's the simplest, not much.
Here is the sample code:

<!--in ASP. Net--><asp:hiddenfield id= "myHiddenField" value= "Shubhabrata"                                             runat= "Server"/><!--in HTML--> <input id= "myHiddenField" type= "hidden" value= "Shubhabrata"/>

Introduction to ASP. NET Cache Usage

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: 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.