Abstract: Introduction to the basic concepts of cache and common cache technology, given a brief introduction and scope of application of various technologies, as well as the problem of design cache schemes (17 pages)
1 concept
1.1 Cache can solve problems
• Performance - Store the corresponding data to avoid repeated creation, processing, and transmission of data, and effectively improve performance. For example, the data that will not change, such as a national list, etc., which can significantly improve the reaction speed of the web program;
· Stability - In the same application, the same data, logic functions, and multiple requests of the user interface often occur. When the number of users is large, if each request is processed, the consumed resource is a lot of waste, and it also causes the system to instability. For example, in a web application, the rendering content of some static pages can be saved to save resources and improve stability. Cache data can also reduce the number of access to the database, reduce the burden on the database, and improve the service capabilities of the database;
· Availability - Sometimes services that provide data information may happen unexpectedly, and if cache technology is used, it can provide the support of end users in a certain period of time, improves the availability of the system.
1.2 understanding
Before introducing the cache technology, there is a matter of understanding, because the cache can be said to be a framework for status management. Understanding the meaning of the status and some of its characteristics - such as survival and living range - have a great help to decide whether to cache and select the appropriate cache technology. Status refers to some data, on a point in time, data, status, and conditions. These data may be permanent stored in the database, which may be only stayed in memory, or it may be in accordance with a logical survival (for example, after releasing), its application range may be accessible, It may be a single user has permission;
1.2.1 Survival period of the status
The survival period refers to the time interval that remains valid, that is, from the time interval created to the removed. The usual survival period has the following:
· Permanent State Permanent State-- the permanent data used by the application;
• Process Status Process State-- only valid within the process cycle;
· Session status session state - and specific user sessions;
• Message Status Message State - Treatment within the time of a message;
1.2.2 range
The range of state refers to physical or logical ranges for access rights to this state.
• Physical range refers to physical locations where the status data that can be accessed, usually:
1. Organization - All applications within an organization can access status data;
2, Field Farm - can be accessed on any machine within the application range;
3, machine Machine - can be accessed within a single machine;
4, process process - access licenses within the process;
5, the application domain appdomain - access license within the application domain.
· The logical range refers to the logical range of accessible status data, common:
1, application Application;
2, business process business process;
3, role Role;
4, user user;
1.2.3 Older status data
The cached status data is just a snapshot of master state data, since the data source may be modified, so status data will have an old characteristic. Rational use this feature and minimize the negative impact of the data is an important task of cache status data. You can define the old basis for the data:
· The possibility of master data changes - how may the primary data change may increase over time? In this point, this is to determine the old exposure of the cache status data; For example, changing the system's appearance style does not have a big impact on the business.
1.2.4 Status Data Old Toba
The influence of cache status data is called tolerance, the application system can be used to tolerance and a certain tolerance, the former must be updated with the primary data, the latter allows for a certain time or A certain range of old, judging criteria is the influence of business processes.
1.2.5 Understanding the conversion process of status data
Another attribute of the state is the form of expression at different stages. The data stored in the database is the original format, and the business process is a processed data, which is presented to the end user is another form. As shown in the following table:
Manifestations
description
Example
Raw data
Original form of data
Data in the database
Handled data
Data after the processed data processing in the business process
Data form in business
Presentation
The form of the end user can be presented
HTML or understandable text description
When determining the cache data, it should be considered to cache which phase (which form) state data. The following policy helps you make decisions:
· When the business logic can tolerate the time of the cache data, the original data can be cached; the original data can be cached in the database access component and service agent;
· Cache processed data to reduce processing time and resources; processable data can be cached in business logic components and service interfaces.
• When the amount of data needs to be presented is large and the rendering time of the control is long, the cache rendering data (such as a TreeView control containing big data). This data should be cached in the UI control.
1.3 Why caoke data?
Cache data in the application has the following benefits:
· Reduce the amount of interaction - Cache data can effectively reduce the amount of transmission between processes and machines;
· Reduce the amount of processing in the system - reduce the number of processes;
· Reduce disk access times that you need to do - such as data in memory.
1.4 Where should data be slow?
The cache data is just a copy of the primary data, which may be saved in the memory in memory or in different manifestations, that is, the closer of the user is, the closer the user. Therefore, in addition to considering which data to cache, where is the main consideration point. This problem is divided into two scope:
1. Storage Type Storage Type-- The physical storage location available for data;
2, the layout of the layout element (Layered Architecture Elements) - the logical storage location available for data.
1.4.1 Storage Type
There are many implementation methods, all of which can be divided into two categories, memory-based cache and disk-based cache:
1. Memory resident cache - all implementations that are temporarily stored in memory, usually in the following cases:
a) The application frequently uses the same data;
b) The application needs to obtain data often;
By keeping data in memory, you can effectively reduce expensive disk access operations, or by keeping data to minimize data transmission across processes in the user process.
2, disk resident cache - this technology contains all cache technologies that use disks as storage media, such as files and databases. The disk-based cache is very effective in the following situations:
a) Handling big data quantity;
b) The data provided by the application service may not always use (such as offline);
c) The cached data must be able to remain valid in the case of process recycling and machine restart;
By cached processed data, you can effectively reduce the burden on data processing while reducing the cost of data interaction. 1.4.2 Architecture Elements
Components of each logical layer in the application processes data, and the figure below identifies some universal components:
When using these components, you need to consider which data can be cached, and which way to cache helps the overall performance and availability of the program, these elements can cache the corresponding data. Of course, it is far more than these.
1.5 Considerations when implementing the cache
When designing a cache scheme, it is not only to consider which data is cached, where the data cache is, there is other factors to consider.
1.5.1 Format and Access Mode
When deciding whether or not to cache an object, you will need to consider three major issues on the format and access mechanism:
1. Thread Safety - When the cached content can be accessed by multiple threads, use a certain lock mechanism to ensure that the data will not be operated simultaneously by two threads;
2, serialization - When a subject is cached, it needs to be serialized to save, so the bundled object must support serialization;
3, normalize the cache data - When the data is cached, the format of the data is optimized relative to the data format to be used.
1.5.2 content loading
Before using the cache data, you must load the data into the cache, there are two mechanisms to load data:
· When loading Proactive Load in advance, when you use this method, you can load all status data into the cache in advance, which may be made when the application or thread is started, and then it is cached during the survival of the application or thread;
· Dynamically load Reactive LOAD - or referred to the reactive load, when using this method, take the data when the application requests data, and caches it to be subsequent use.
1.5.3 expiration strategy
Another key factor is how to maintain the consistency of cache data and primary data (files or databases, or other application resources), you can define expiration policies to determine the content in the cache, such as cached time or receive other resources. Notice.
1.5.4 security
When cache data, you need to know the potential security threat of data in the cache. The data in the cache may be accessed or modified by other processes, and this process is no permissions to main data. The reason is that when the data is stored in the original position, there is a corresponding security mechanism to protect it. When the data is brought out of the traditional security boundary, there is a need for equal security mechanisms.
1.5.5 management
When you cache data, the maintenance work required by the application system is increased. When publishing an application, you need to configure the appropriate properties, such as cache limits and clearing policies. Also use a mechanism to monitor the efficiency of the cache (such as event log and performance counter)
1.6 small knot
The first section briefly introduces the concepts, cache data, and the reasons, advantages, advantages, and considers of the cache scheme. Now you have a general understanding of the content involved in the cache, focusing on the available cache technology.
2 cache technology
This section describes the following techniques:
Use the ASP.NET cache;
Use Remoting Singleton to cache;
Use memory map files;
Use SQL Server cache;
Use a static variable cache;
Use the ASP.NET session status (session state);
Use the ASP.NET client cache and status;
Use Internet Explorer cache.
2.1 ASP.NET cache
Save the commonly used data in memory is not strange to the developer of ASP. The session object and Application object provide key value pair to cache data, session object saves and individual users, and Application objects can be reserved and the application is related. Data, each user can access. In ASP.NET, a Cache object specifically used to cache data is provided, and its application range is the application domain. The survival period is closely related to the application, and whenever the application is started, recreate the Cache object. The main difference between its domain Application objects is to provide features, such as dependent and expiration strategies specifically for cache management.
You can use the cache object and its properties to implement advanced cache functions, and can use ASP.NET Cache to cache the response content of the client output. About cache technology in ASP.NET, have the following contents to introduce:
2.1.1 Programming Cache Programmatic Caching
The Cache object defines the namestem.Web.caching namespace, you can use the cache attribute of the HTTPContext class or the cache property of the Page object to get the cache reference, and the Cache object can store the object of the .NET framework in addition to the storage key value pair. The corresponding dependency and expiration strategy will be described below.
2.1.1.1 Dependency and expiration strategy
When adding data to the cache, you can specify its dependencies to implement in some cases to force remove it. Available schemes include the following:
· File Dependency - Forced Cache data when certain (some) file changes on the hard disk; such as:
CachedPendency CDependency = New
Cachedependency (Server.MAppath ("Authors.xml"));
Cache.insert ("CachedItem", Item, CDependency;
• Key Dependency - Removes a certain data item change in the specified cache. Such as:
// CREATE a cache entry.
Cache ["Key1"] = "Value 1";
// Make Key2 Depndent on key1.
String [] DependencyKey = new string [1];
DependencyKey [0] = "key1";
Cachedependency Dependency = New Cachedependency (Null, DependencyKey);
Cache.Insert ("Key2", "Value 2", Dependency);
· Time-based expiration strategy - to make data failure according to a pre-defined time policy, can be absolute time (18:00 at a certain date) or relative time. Such as:
/// Absolute eviration
Cache.insert ("CachedItem", item, null, datetime.now.addseconds (5), cache.noslidingexpiration;
/// Sliding expiration
Cache.Insert ("CachedItem", item, null, cache.noabsoluteExpiration,
Timespan.fromseconds (5));
It is not possible to use too short and too long expiration. It is not a cache data that can't be used. It is to cache old data and add a cache burden, so high-concurrent testing can be used to determine the optimum value of the expiration time. · Another question is how to implement the dependence on the database, which requires its own notification mechanism, which can notify you of the cache data change when the database data changes. Refer
An example of http://www.gotdotnet.com/team/rhoward.
Since the data expires, the data is valid when using data in the cache. Such as follows:
String data = (string) cache ["myitem"];
IF (data == null)
{
Data = getData ();
Cache.Insert ("MyItem", DATA);
}
DOSMETHINGWITHDATA (DATA);
Dependency and expiration strategies specify the removal method of data in the cache, sometimes you may need to do some jobs when you remove it, this is what we have to say.
2.1.1.2 Using Cache Tutance (Cache Callback)
You can define a callback, so when you remove it automatically, you may not remove it or use new data to replace it. Such as:
CacheItemRemovedCallback onremove = new cacheItemRemovedCallback (this.removedCallback);
Cache.insert ("CachedItem",
Item,
NULL,
Cache.NoabsoluteExpiration,
Cache.noslidingexpiration,
CacheItemPriority.default,
Onremove);
// Implement the function to handle the expected of the cache.
Public void RemovedCallback (String Key, Object Value, CacheItemRemovedreason R)
{
// Test WHETHER THE ITEM IS EXPIRED, And Reinsert It Into The Cache.
IF (r == cacheItemRemovedreason.expired)
{
// reinsert it in the cache again.
CacheItemRemovedCallback onremove = null;
OnRemove = New CacheItemRemovedCallback (this.RemovedCallback);
Cache.insert (Key,
Value,
NULL,
Cache.NoabsoluteExpiration,
Cache.noslidingexpiration,
CacheItemPriority.default,
Onremove);
}
}
2.1.1.3 Use priority to the cache item
When running the application's server memory, the data in the cache is automatically cleared, called "Clear Scavenging". At this point, the Cache object determines which cache data is removed according to the priority of the cache item, and you can specify the priority of the cache item in your code. See "CacheItemPriority Enumeration" in MSDN, such as:
Cache.Insert ("DSN", Connectionstring, Null, D, T, CacheItemPriority.High, Onremove;
2.1.1.4 Refresh Data (Clear Cache) There is no direct method to refresh the output cache of ASP.NET, but there is an alternative method (set all data failures), such as:
Response.cache.sexpires (datetime.now)
This can clear the cache, but do not immediately refer to the page until the end of the initial buffer period, such as:
<% @ Outputcache duration = "10" VarybyParam = "NONE"%> The cache specified by the instruction will only be cleared after 10 seconds. Usually do not need to clear all buffers, you will be enough to reload the data update cache.
2.1.2 Output Cache (OUTPUT CACHE)
You can use the output cache of two ways to cache data-page output caches that need to be transferred and displayed on the client browser (Page Fragment Cache). When the entire page is relatively small, the entire page can be cached; if it is only a part of the page, a clip cache can be used.
2.1.2.1 Page Output Cache
Page Output Caching Put the response to the page request in the cache, follow-up requests for this page to get information directly from the cache rather than rebuilding this page. You can implement it by adding a PAGE instruction (high-level, declarative implementation), you can also use the HTTPCACHEPOLICY class to implement (low level, program implementation). This guide is not intended to introduce technical details, and only give guides and best practices for how to better use. There are four aspects:
1, determine the content of the cache
The page output cache can cache various information, cache this information means you don't need to process the same data and results, including:
· Static page that is often requested but does not change;
· Update the frequency and time known page (such as a page showing stock price);
· According to the HTTP parameters, there are several pages that may be output (such as displaying the city's weather conditions on the city);
· Results returned from Web Service;
[WebMethod (cacheduration = 60)]]
Public String HelloWorld ()
{
Return "Hello World";
}
2, cache dynamic page
Dynamic web pages based on input parameters, language, and browser types are often used. You can use the following properties of OutputCache to implement the cache for the dynamic page:
VaryByParam - multiple versions of the same page based on the input parameters;
VarybyHeader - multiple versions of different cache pages based on page header;
VarybyCustom - Customize multiple versions of the cache processing page by declaring attributes and overloading the getvaryByCustomString method;
VarybyControl - Cache controls based on the ASP object properties in the control.
The cache for multiple versions will reduce the available memory, so you need to measure the cache policy. s
3, control the location of the cache
You can use the enumeration value of the OutputCacheLocation property of the @outputCache directive to specify the location of the cache, such as:
<% @ Outputcache duration = "10" VarybyParam = "none" location = "server"%>
4, configure the page output cache
There are two ways to control, you can use the PAGE directive, you can also use the Cache API programming. Refer to the following two codes: // Code 1, use instructions
<% @ Outputcache duration = "20" location = "server" varybyparam = "state" varybycustom = "minorversion" varybyheader = "accept-language"%>
// Code 2, programming implementation
Private Void Page_Load (Object Sender, System.EventArgs E)
{
// Enable Page Output Caching.
Response.cache.setcacheability (httpcacheability.server);
// set the duration parameter to 20 seconds.
Respire.cache.sexpires (system.datetime.now.addseconds (20));
// set the header parameter.
Response.cache.varybyheaders ["acche"] = true;
// set the cached parameter to 'statE'.
Response.cache.varybyParams ["State"] = true;
// set the customer parameter to 'minorversion'.
Response.cache.setvarybycustom ("minorversion");
...
}
2.1.2.2 Page Diaches Cacked
Sometimes it is not flexible to cache the entire page, while the memory is sent, but also relatively large, this should consider the clip cache. The page tablet breaks the following types of data:
· Create a page piece break (control) that has a large overhead;
· Page piece breaks containing static data;
· Page blockage can be used by multiple users;
· Multiple pages shared page pieces (such as utility menu bar)
The following is an example of a cache section:
// Partial Caching for 120 Seconds
[System.web.ui.partialCaching (120)]]
Public Class WebUserControl: System.Web.ui.userControl
{
// Your Web Control Code
}
2.1.3 Using ASP.NET cache in non-Web projects
ASP.NET Cache is located in System.Web namespace, but because it is a universal scheme, it is still possible to use it in any non-Web project referenced to this namespace.
The system.Web.caching.cache class is an object's cache, which can be accessed via system.Web.httPruntime.cache's static properties or system.web.ui.page and system.web.httpContext.cache. Therefore, in the request context, only one instance is in each application domain, so the httpruntime.cache object can exist in each application domain other than ASPNET_WP.exe. The following code demonstrates access to the cache object in normal applications:
HTTPRUNTIME HTTPRT = New httpruntime ();
Cache cache = httpruntime.cache;
2.2 Using Remoting Singleton Cache
.NET Remoting provides a cross-application domain, cross-process, procedure running framework across computers. The server-activated object has two activation modes, where the Singleton type does not have multiple instances at the same time. If there is an instance, all client requests are served by the instance. If there is no instance, the server will create an instance, while all subsequent client requests will be served by this instance. Since the Singleton type has the associated default life, even if there is any available instance at any time, the client does not always receive references to the same instance of the category that can be processed. Therefore, cache the data can be shared between multiple clients.
In order to use the .NET Remoting implementation cache scheme, to ensure the lease of the remote object is not expired, and the remote object is not destroyed by the garbage collector (the object lease means that it is in memory before the system is deleted). When the cache is implemented, the MarshalByrefObject's initializelifetimeservice method is overloaded and NULL can be returned so that the lease will never perform in the expectations and the related object survival is unlimited. The following code is an example:
Public Class DataSetStore: MarshalByrefObject
{
// a Hash Table-Based Data Store
Private hashtable htstore = new hashtable ();
// Returns a null lifetime manager so that gc won't collect the object
Public override Object InitializelifetimeService () {Return Null;}
// Your Custom Cache Interface
}
Note: Due to the high cost of this solution, the performance of the SQL Server-based scheme is usually used by the system unstable.
2.3 Using a Memory-Mapped File
Memory map files provide unique features that allow applications to access files on disk through pointers - the same way as accessing dynamic memory. So you can map the data of an address segment in the application process to a file for multiple across application domains or cross-trip access.
In Windows, code and data are processed in way, the expression is a memory page, and behind the internal storage page is files on the disk. Unique file types on different disks are different. The code is later is an executable mirror, and the data is behind the system's page file. When multiple applications share memory, the performance of the system will be significantly improved.
You can use this feature of memory map files to implement cache solutions across processes and cross-care program domains on the same machine. The cache scheme based on memory mapping files contains the following components:
· Windows NT Service - Create a memory mapping file when starting, and delete it when it is stopped. The function is to provide a handle to the process using the cache. Of course, you can also use the named memory map file to provide an operation interface;
· Cache Management DLL - implement specific cache functions, such as:
a. Insert and delete data items into the cache;
b. Use the algorithm to clear the cache, such as the last use algorithm;
c. Guaranteed data is not tampered;
Cache scheme based on memory mapping files can be used in each layer of the application, but is not easy to implement because of the Win32 API call. The .NET frame does not support memory mapping files, so it can only be operated in a non-hosting code, and of course, the powerful characteristics of the .NET framework can be used, such as garbage collection. At the same time, the management function of the cache data item needs to be customized, and it is also necessary to develop performance counters to monitor the effect of the cache. 2.4 Use SQL Server Cache
If you need to be recycled (restart), the machine restart, or the power failure is required to keep the cache data is valid, the memory-based scheme cannot meet the requirements. You can use a permanent data store, such as a SQL Server database or NTFS file system.
SQL Server When using the SQL statement or stored procedure, SQL statement or stored procedure has 8K size limits, you must use the ADO.NET SQLDataAdapter object provided by the .NET framework to access the DataTable or DataSet.
Advantages of using SQL Server cache data:
· Easy to implement - Access the database using the .NET framework and ADO.NET;
· Perfect safety model and high robustness;
· The data is very convenient;
• Data's lasting retention.
· Supports a lot of data.
· Convenient management tool
Of course, there are also disadvantages:
· It is necessary to install SQL Server, which is not suitable for small applications;
· Re-constructing data performance and reading database performance comparison;
· Network burden.
2.5 Use static variable cache
Static variables are often used to record the state of the class, you can use it to create a custom cache object. Declare your data memory as static variables in custom cache classes, and provide maintenance interfaces (insert, delete, and access, etc.). It is convenient to use static variable cache data if there is no special cache requirements (such as dependence, failure policies, etc.). Since it is in memory, this scheme can provide direct, high-speed access to cache data, and static variables can be used when there is no replacement to resolve the storage of key value pairs and high speed requirements. Of course, in ASP.NET, Cache objects should be used.
You can use this scenario to save big data objects, provided that it does not change frequently. Since there is no clearing mechanism, the memory consumption of big data will affect performance.
You need to guarantee custom thread security mechanisms or synchronization objects provided by the .NET framework, such as HashTable. The following code is an example of using a HashTable:
Static hashtable mcachedata = new hashtable ();
Application range: The application range of this program can be limited to class, module or whole project. If the variable is defined as public, the code in the entire project can access it, the range is the entire application domain, and efficient sharing is implemented. It is closely related to its survival.
2.6 Using ASP.NET Session State
You can use an ASP.NET Session State based on HTTPSessionState object to cache session status information for a single user. It solves a lot of restrictions on session status in ASP, including:
· ASP session requires the client to accept cookies, otherwise the session cannot be used; and the ASP.NET can be configured to not use cookies;
· The situation of the Web Server field, the SESSION of ASP cannot be supported; when the stability and usability requirements are high, the ASP.NET Session State is not good, but the relatively small single value Scalar Value (such as login information), or very effective. ASP.NET session has great improvements, which describes the use and way of use.
ASP.NET Session State has three operating modes:
1, the process of internal mode inproc - session state information stores in the memory of the process_wp.exe of the ASP.NET work process. This is the default option. In this case, if the process or application domain is reclaimed, the session status information is also reclaimed;
2, the proDelm mode STATE SERVER - Status Information Sequence Save in a separate state process (ASPNET_STATE.EXE), so status information can be saved on a dedicated server (a status server State Server);
3, SQL Server mode - Status information sequence is saved in the SQL Server database.
You can set the status mode to use by adjusting the Mode property of the
2.6.1 Select the mode of use
2.6.1.1 Using Inproc mode
When using internal mode mode, status information is saved in the process of ASPNET_WP.EXE. Since multiple instances of ASPNET_WP.EXE run on the same server in the case of a web field, the internal mode is not applicable to the Web field.
The internal mode is the only session mode that supports the session_end event. When the user session is timeout or abort, you can run the event processing code in session_end to clear the resource.
2.6.1.2 Using StateServer mode
The StateServer mode uses the specified process to store status information. Because it is also a processes, it is necessary to ensure that the object you store is serialized to support cross-process transfers.
When using the Session object in the case of a Web field, you must ensure that
2.6.1.3 Using SQL Server mode
SQL Server mode When you use a trust connection (Trusted_Connection = true or integrated security = SSPI) Access Session State information, you cannot use your identity user simulation in ASP.NET.
By default, SQL Server stores status information in the TEMPDB database, which is automatically recreated at each SQL Server service startup, of course, you can specify your own database to keep data during the database restart.
2.6.2 Decide to use the session object to be stored
You can use the Session object to cache any type of .NET framework data, but you have to know what is the best way to some types. There is a shortest note:
1. Use any way for basic types (such as int, byte, string). Because ASP.NET uses an optimized internal method to serialize and reverse sequencing the basic type of data using an optimized internal method; Because ASP.NET uses binaryformatter to serialize and deserialize such data, this will affect performance. Of course, serialization operation is only performed in the way State Server and SQL Server;
3, the security problem of cache, when you store sensitive data in the cache, you need to consider security, and other pages can access data in the cache;
4. Avoid cache big data, which will reduce performance;
5, this kind of cache does not support expiration strategy, clearing, and dependence.
2.6.3 Implementation STATE
ASP.NET provides simple interface to operate session state, and you can use Web.config for simple settings. When setting in the configuration file changes, it can be reflected on the page without the need to restart the ASP.NET process.
The following code demonstrates the storage and use of session data using SQL Server.
Mode = "SQLServer" StateConnectionstring = "TCPIP = 127.0.0.1: 42424" SqlConnectionstring = "data source = 127.0.0.1; integrated security = sspi" Cookieles = "false" TIMEOUT = "20" /> Private void Savesession (String CartID) { Session ["ShopPingCartID"] = CARTID; } private void checkout () { String CartID = (String) Session ["ShoppingCartID"]; IF (CARTID! = NULL) { // Transfer Execution To Payment Page. Server.Transfer ("payment.aspx"); } Else { // Display Error Message. } } 2.7 Use the ASP.NET client cache and status You can also use the client to store page information to reduce the server's burden, which provides the lowest security, but there is the fastest performance. Since the data needs to be sent to the client storage, the amount of data is limited. There are five types that implement the client cache, and will be introduced next: · Hidden Field (Hidden Field) View State · Hidden frame (Hidden Frame) · Cookies Query String These five methods are respectively suitable for storing different types of data. 2.7.1 Using Hidden Field You can save a small amount of data that frequently changed in HTMLINPUTHIDDEN to maintain the status of the page. When each page is looped, these data will be included in the form to the server, so you have to use the HTTP POST method to submit the page. The advantages of using this method are as follows: No server resources are required, read directly from the page; Almost all browsers are supported; simple implementation; Since the data is in the page, it can be used in the case of Web Farm. Disadvantages: Since it can be seen by viewing the source code, it may be tampered with; Data that does not support complex formats, complex data must be indirectly obtained by parsing strings; When the big data is stored, it will affect performance. Example: 2.7.2 Using View State All Web Form pages and controls contain a ViewState property that keeps the value in the page when requesting the same page multiple times. Its internal implementation is to maintain the corresponding Hidden Field, but it is only encrypted, so it is better than Hidden Field. Performance using View State depends largely on the type of server control. In general, Label, TextBox, Checkbox, Radiobutton, HyperLink's performance is better, and DROPDOWNLIST, ListBox, DataGrid and DataList are a lot, because the amount of data is too large, so each page returns take time. In some cases, you don't recommend itState, such as: 1. You don't need to return to the page to avoid use; 2. Avoid using ViewState to save large data; 3. Avoid usage when you need to use a session timeout because it doesn't time out. ViewState's performance performance and Hidden Field are similar, but higher security. advantage: Data is automatically maintained in the page without the need for server resources; Simple implementation; The data is encrypted and compressed, which has higher security than Hidden Field; Data has a client, which can be used in the case of Web Farm. Disadvantages: Reduce performance when storing large data; Similar to Hidden Field, there is still a potential security threat in client data. The sample code is as follows: Public class viewstateSample: system.web.ui.page { Private Void Page_Load (Object Sender, System.EventArgs E) { IF (! page.ispostback) { // Save Some Data in The ViewState Property. THIS.VIEWSTATE ["Entertime"] = datetime.now.tostring (); THIS.VIEWSTATE ["UserName"] = "john smith"; THIS.VIEWSTATE ["country"] = "USA"; } } ... Private void btnrefresh_click (Object Sender, System.EventArgs E) { // Get The Saved Data in The View State and Display IT. THIS.LBLTIME.TEXT = this.viewState ["Entertime"]. TOSTRING (); THISLBLUSERNAME.TEXT = this.ViewState ["username"]. TOSTRING (); this.lblcountry.text = this.viewState ["country"]. Tostring (); } } 2.7.3 Using Hidden Frame You can use Hidden Frame to cache data in client, which avoids cache data round trips when using the Hidden Field and using View State. For example, you can secretly load the images you need to load multiple pages, which does not consume server resources. advantage: a. You can load more data instead of just a single field value; b. Avoid unnecessary data exchanges in multiple returns; c. You can cache and read data items stored in different forms (data that can cache multiple pages at the same time); d. You can access the client script data in the same site different frame. Disadvantages: a. Some browsers do not support Frame; b. Source code can be seen at the client, there is a potential security threat; c. The number of hidden frames is not limited. If the frame page contains more Hidden Frame, there will be limitations in the first load. The sample code is as follows: