Asp. NET Cache Management Methods _ practical skills

Source: Internet
Author: User
Tags require serialization browser cache

Although cache management is no longer a problem in Windows applications, it is still a challenge in the web environment. Because HTTP is a stateless protocol and the Web service does not recognize the users of different requests. It is important for us to identify which particular user is sending the different requests and to store the information so that it can be reused in future requests. Asp. NET provides many features to store this data on both the client and server side, but sometimes we wonder "when we use them." In, we encounter objects like session,application and cache, and it is important for us to understand the differences between them in order to effectively use them in Web applications.


In this article, I'll talk about different ways of caching management in In Web applications, it is sometimes necessary to store data on the server side to avoid the overhead required to retrieve data and data formatting logic from the database, while in the next request we can reuse the same data across users, across applications, and across machines. So, in order to do this we need to cache data on the server side.

Caching helps us achieve improved quality of service in 3 areas

• Performance (performance)-Caching improves application performance by reducing retrieval data and formatting operating costs.
• Scalability (scalability)-because caching reduces the overhead of retrieving data and formatting operations, it lowers the load on the server side, thereby increasing the scalability of the application.
• Availability (availability)-applications can continue to run when other systems or database connections fail because the application reads data from the cache.
Different methods

In Web applications, we can cache data, pages, and so on both the server and the client. Let's look at the server side and the client cache separately.

Server-side Cache management session state

Session is used to cache information for each user. This means that the data is not shared across users, and it only limits the users who created the session to use it. Asp. NET session is used to differentiate users.

Sessions can be hosted in three different ways:

• In-process (INPROC)-session state is stored in the Aspnet_wp.exe process. Session data is lost when the application domain is reclaimed.
• State server (StateServer)-session state is stored in different processes and can be on different machines. Because it can be stored on different machines, this option supports the site group.
SQL database (SQL Server)-session state is stored in the SQL Server database, and this option also supports the site farm.
Both the state server and the SQL database require serialization of cached objects because the data to be cached is cached outside the application process. Both of these ways can affect performance because data retrieval and storage require more time relative to the process cache. Therefore, depending on your needs, determine which caching method to use.

The following sample code shows how to use the session

Copy Code code as follows:

String empnum = request.querystring["Empnum"];
if (empnum!= null)
string details = null;

if (session["emp_details"] = = null)
Get employee Details for employee number passed
Details = Getemployeedetails (Convert.ToInt32 (empnum));

session["emp_details"] = DETAILS;
Details = session["Emp_details"];

Send it to the browser
Response.Write (Details);
} Application Object

Asp. NET provides an object called application to store data that is accessible to all users. The life cycle of this object is the same as the lifecycle of the application, and the object is recreated when the application starts. Unlike the session object, the Application object can be requested by all users because the object is created and managed in the application domain and therefore cannot be used in a Web site farm. The Application object is ideal for storing application metadata (Config file data), which can be loaded into the Application object and can be accessed by each user request throughout the application cycle without reloading. However, if there is such a requirement: no matter when the application is in operation to modify the config file cache data must be invalidated, then the application method can not provide such support. In this case, it is necessary to consider the cache object, the following describes the use of the cache object. cache Object cache object is my favorite caching mechanism, which is why I am here to say a few more reasons. Asp. NET provides a key-value pair (Key-value pair) object--cache object that can be obtained in the System.Web.Caching namespace. It is scoped to the application domain, and the lifecycle and application lifecycle are consistent. Unlike the session object, it can be accessed by different users.

Although application and cache objects are very similar, the main difference is that the cache object has more features, such as expiration policy, cache dependency. It means that the data store expires or is clear when the cached object can change depending on the predefined time or the entity it depends on, and this attribute application object is not supported.

Let's discuss the expiration policy and the caching dependencies it supports.

Depend on

Dependency means that the cached object is purged when the dependent entity is changed. So you can define a dependency to clear the corresponding cache object when the dependent object changes. Asp. NET supports two kinds of dependent objects.

• File Dependencies-it provides a mechanism to automatically purge cached objects whenever a disk file changes Dependency. For example, my application uses XML to store error messages (the mapping of error numbers and error messages) with an error number to retrieve the error message. Every time I try to read the error message, I don't read it from disk every time, but when it is started, it is put in the cache so that it can be retrieved later. What happens when I add a new error message or modify an existing error message while the program is running? Do I need to stop the program running to modify this information? Not at all, when you modify this, the data in the cache is automatically invalidated, which is the file cache dependency.
The following example shows how to use the file cache to disable cache caching. So, whenever you make a modification to a error.xml file, the cached entry will automatically expire.

Copy Code code as follows:

Object ErrorData;
Load ErrorData from Errors.xml
CacheDependency filedependency =
New CacheDependency (Server.MapPath ("Errors.xml"));
Cache.Insert ("Error_info", ErrorData, filedependency);

• Key-dependent (key Dependency)-dependency and file dependencies are very similar, the only difference is that it is not dependent on the file but on other entries, when the cache-dependent entry changes or deleted, the cache will automatically expire. This approach increases the number of interdependent objects into the cache, and is useful in situations where the dependent cache objects are freed when the primary object is changed. For example, the employee number, name, and salary are added to the cache, and if the employee number has changed or been deleted, all employee information in the cache will be purged. In this example, the employee number acts as a dependency in the employee information.
The following example shows how to use key dependencies to invalidate a cache.

Copy Code code as follows:

string[] Relatedkeys = new String[1];
Relatedkeys[0] = "Emp_num";
CacheDependency keydependency = new CacheDependency (null, Relatedkeys);
cache["Emp_num"] = 5435;
Cache.Insert ("Emp_name", "Shubhabrata", keydependency);
Cache.Insert ("Emp_addr", "Bhubaneswar", keydependency);
Cache.Insert ("Emp_sal", "5555USD", keydependency);

Expiration policy (Expiration Policy)

The expiration policy defines how and when to let cached objects expire.

• Based expiration (time expiration)-a time based expiration provides a time when a user is predefined to cache an object. This predefined time can be an absolute time such as 12 O'Clock October 31, 2005, or relative time, relative to the cached object's deposit time.

Copy Code code as follows:

Absolute expiration
Cache.Insert ("Emp_name", "Shubhabrata", NULL,
DateTime.Now.AddDays (1), cache.noslidingexpiration);

Sliding expiration
Cache.Insert ("Emp_name", "Shubhabrata", NULL,
Cache.noabsoluteexpiration, Timespan.fromseconds (60));

How do I know that a cached object is cleared?

The above example describes how to clear cached objects, but sometimes we need to know when objects are purged from the cache. OK, we do this by using callbacks. In the example of the error message above, the cached object is purged whenever the error.xml changes. Suppose we want to update the cache with the latest error message. When the object is purged from the cache, we can use the callback (Callback) for further processing (reloading the object into the cache).

The following example shows how to use a callback scenario when the cache expires.

Copy Code code as follows:

private void Additemstocache ()
int empnum = 5435;
CacheItemRemovedCallback Onempdetailsremove =
New CacheItemRemovedCallback (empdetailsremoved);
Cache.Insert ("Emp_num", Empnum, NULL,

private void empdetailsremoved (String key, Object Val,
CacheItemRemovedReason reason)
When the item is expired
if (reason = = cacheitemremovedreason.expired)
Again add it to the Cache
Additemstocache ();<br>}

In the example above, you must pay attention to cacheitempriority this parameter, which is used with the callback parameter. CacheItemPriority is used to set the priority of an object added to the cache. This priority tells the cache that when memory is low, this priority indicates the order in which the objects are released. This process is called purge (scavenging).

. NET Remoting

You might think. NET remoting how to use the data cache? When I first heard the question, the question came into my mind. As you know. NET Remoting shares objects to individual clients through a single example, so objects using a single instance can be used to cache data to share data with different clients. Because. NET remoting can run outside of processes and machines, this feature is useful when we want to cache objects and across services, across users, and especially in site groups. This method allows us to cache data into the data members of a single object and provide a way to read and store the data. When we implement this approach, we must ensure that the cached remoting object is not purged by the garbage collector. So we have to set the cache for the remoting object to never expire and never time out. We can override the InitializeLifetimeService and MarshalByRefObject methods to make them return null. But the main problem with this is performance, which is less performance than other methods through analysis. In any case, the designer or developer should choose the most appropriate method based on the specific requirements.

Memory-mapped files (memory-mapping files)

You know what a memory-mapped file is, based on a specific address range that maps to a file on a physical disk to the application's storage space. This approach allows different processes to use the same data to increase application performance. Because using memory-mapped files is not prevalent in applications, I personally do not recommend this approach because it increases the complexity of the program and is not supported by the. NET Framework. But if someone likes to use this method, he must develop a defined solution for their needs.

static variable (variables)

We can use static variables to store global data or objects in order to access it throughout the application life cycle. Similarly, we can use static objects to cache data, and we can provide methods to retrieve and store data from the cache. Because static objects are stored in the process, performance is very fast. But using static variables to implement expiration policies and cache dependencies is very complex, and I prefer to use cache compared with static variables. Another problem is that user-defined cache objects must be thread-safe, so implementing it must be particularly cautious.

Custom static caching can be implemented in the following ways:

Copy Code code as follows:

public class Customcache
Synchronized to implement Thread-safe
static Hashtable _mycache =
Hashtable.synchronized (New Hashtable ());

public static object GetData (Object key)
return _mycache[key];

public static void SetData (Object key, Object val)
_mycache[key] = val;


We can use a database to store data to enable cross user, cross machine data sharing. When we want to cache very large data objects, this is a very good way. Storing small amounts of data in this way is not worth it (performance is low) and is used to store a small amount of data to look for caching mechanisms in other processes. Cached data stored in a database needs to be serialized into XML for easy storage and retrieval, and other types of serialization formats can be used in the. NET framework.

Page out cache ( page output caching)

Sometimes our web applications will not change for certain pages within a certain timeframe, for example, in HR sites, Employee payroll information is not frequently changed, and they are typically changed only once in one months. In general, the first day of the one-month change. So, for a particular employee, the page content of the employee is unchanged for one months. So it's a good idea to cache these pages on the server to avoid each request for recalculation. In order to achieve this goal,. NET provides us with the characteristics of specifying a cached output page for a specific time on the server side, and it also provides the characteristics of caching page fragments. I'm not going to describe this caching method in detail here, because there's a lot of detail on the web. This is a very long part if we talk about it now, I plan to discuss it in other chapters.

Copy Code code as follows:

<!--varybyparm-different versions of same page would be
Cached based on the parameter sent through HTTP get/post
Location-where the page is cached-->
<% @OutputCache duration= "varybyparam=" Empnum "
location= "Server"%>

Let's compare the caches we're talking about:

Method Do you support site groups? Note session state
-SQL Server


Unlike option, it stores only the user session specific data application Object No Cache Object No
. NET Remoting Yes
memory-mapped files No
Static Variables No
Database Yes Page Output Caching No

Client Cache Management

In the previous section we discussed the way of caching on the server side, but sometimes we want to cache data and pages on the client to improve performance. Using client-side caching can reduce the load pressure on the server, but there is a security problem with this caching mechanism because the data is stored on the client. There are also different ways of caching in the client, and I will briefly talk about several.


Cookies are very familiar concepts to web developers, and cookies are stored on the client and sent to the server each time the client sends a request, and the server sends it back to the client when it responds. Because it restricts the number of bytes (4,096 bytes), it can only cache relatively small data. It can use an expiration policy to invalidate it after a certain period of time. The following example shows how to use cookies in

Copy Code code as follows:

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


The. NET viewstate is a new concept. The data and controls associated with the page are stored in ViewState, which can span multiple request-path servers. If you remember, storing data across multiple requests in vb-asp application development is through the hidden control. In fact viewstate in is the inner implementation of the hidden control, but it is hashed to increase security by contrasting the hidden controls. To see how viewstate is implemented, you can open the page to view the source code. ViewState also cannot store large amounts of data because each request is sent to the server.

Copy Code code as follows:

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 ();

Hidden fields

Hidden field is very popular in vb-asp web development. Hidden fields is very similar to other controls, but it is not visible on the output page. Like ViewState, it cannot store large amounts of data. Note: Hidden frames (Hidden frames) can cache data on the client, but not all browsers support hidden frames.

Copy Code code as follows:

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

Microsoft IE Browser cache

Because we are talking about Microsoft's, why not discuss Microsoft's other caching capabilities? Microsoft's IE browser provides another mechanism for caching pages on the client, which can be added to HTML pages using the expires settings directive or manually set in IIS. To the HTTP Label Properties window in IIS, and then select the Make content expire check box. We can use this setting to cache static pages and pictures on the client.

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.