Abstract: Introduction to the basic concepts of cache and common cache technology, given a brief introduction and scope of application of various technical implementation mechanisms, as well as the problem that should be considered by the design cache scheme (17 pages) 1 Concept 1.1 Cache can solve Problem • Performance - Store the corresponding data to avoid duplicate creation, processing, and transmission of data, and effectively improve performance. For example, the data that does not change will be cached, such as a list of national lists, etc., which can significantly improve the reaction speed of the web program; • In the same application, the same data, logic functions, and user interface often occurred during multiple requests. of. 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. The cache data can also reduce the number of access to the database, reduce the burden of the database, and improve the service capability of the database; • Availability - Sometimes the service providing data information may stop, if the cache technology can be used, can be used for a certain period of time It is still necessary to provide support for end users, improve system availability. 1.2 Understanding Status Before introducing the cache technology, there is a matter of understanding, because the cache can be said to be a framework of 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 permissions; 1.2.1 The living life of the status is the time interval that maintains validity, that is, from the time interval created to the removed. The usual survival period has the following: • Permanent Permanent State-- The permanent data used by the application; • Process status Process State-- only valid in the process cycle; · Session status session state - and specific user sessions • Message Status Message State - Processes the time within a message; 1.2.2 Scope of the state of the state refers to the physical or logical range of access rights to this state. · Physical range refers to physical locations that can be accessed, usually: 1. Organization - Organization - all applications within one organization can access status data; 2, Field Farm - within the application range Access on any machine; 3, machine Machine - can be accessed within a single machine; 4, access licenses within the process process; 5, the application domain appdomain - the 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 status data of old cache status data It is just a snapshot of master state data. Since the data source may be modified, status data will have an old character. Rational use this feature and minimize the negative impact of the data is an important task of cache status data.
You can define the static basis for the data in a manner: • The possibility of main data changes - whether the primary data change may increase? 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 Tolerant Cache Status Data The influence of the business process is called tolerance, the application system can be tolerance and a certain tolerance, the former must and the main data Synchronous updates, the latter allows for a certain amount of time or a range of strangers, the criteria is the influence of the business process. 1.2.5 Another attribute of the conversion process status of the state data 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: Describe the form of the original data data of the original data data, such as the data processed data service process in the database, in the form of data in the data business process after the original data, can be presented to the final user's form HTML Or understandable text Description When determining the cache data, the state data of which phase (which form) is cached. The following policy helps you make decisions: • When the business logic can tolerate the display 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 The processed data can be cached in the service logic component and the service interface. • 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 cao is cache data Cache data in the application: • Reduce interaction traffic - Cache data can effectively reduce the transfer amount between processes and machines; • Reduce the processing amount in the system - reduce the number of processing; · Reduce disk access times that you need to do - such as data in memory. 1.4 Data should be cached where the cache data is just a copy of the primary data, which may be saved in the memory or in different manifestations, that is, the closer of the user is, the closer 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 of the following: 1, the storage type Storage Type - data available physical storage location; 2, the layout architecture element of the interlayer (Layered Architecture Elements) - the logical storage location available for data. 1.4.1 Storage Type Cache has 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 of temporary storage data in memory, Usually use: a) Applications frequently use the same data; b) The application needs to obtain data frequently; by retaining data in memory, you can effectively reduce expensive disk access operations, or reserved data To maximize data transfer 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.
In the following cases, the disk-based cache is very effective: 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 process Recycling and machine restarts are maintained; through cache processing data, you can effectively reduce the burden of data processing while reducing the cost of data interaction. 1.4.2 Components of each logical layer in the architectural element application process data, the following figure identifies some general components: When using these components, you need to consider which data can be cached, and where is it The cache is helpful to help the overall performance and availability of the program, and the above elements can cache the corresponding data. Of course, it is far more than these. 1.5 Considering the Cache When designing a cache scheme, not only, not only, where the cache is to be cached, where the data is cached, there is other factors to consider. 1.5.1 Format and Access Mode When deciding whether or not to caches an object, the format and access mechanism of the data, you need to consider three main issues: 1. Thread security - When the cached content can be accessed by multiple threads, use A certain lock mechanism guarantees that data is not simultaneously operated by two threads; 2, serialization - When a object is cached, it needs to be serialized it to save, so the bundle of buckover must support serialization; 3, Specificization Cache data - When data is cached, the format of the data is optimized relative to the data format to be used. 1.5.2 Content Load Before using the cache data, you must load the data into the cache, there are two mechanisms to load data: • Load Proactive Load in advance When using this method, you will load all status data into the cache in advance. In the application or thread start, then it is cached during the survival of the application or thread; • Dynamically load the Reactive Load - or refer to the reactive load, when using this method, request data in the application Take data and cache it up for subsequent use. 1.5.3 Expired Strategy Another key factor is how to maintain the consistency of cache data and primary data (file or database or other application resources), you can define expiration policies to determine the content in the cache, such as the time that has been cached or Receive a notification from other resources. 1.5.4 Security When cache data, it is necessary to very clear potential security threats 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 caching 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. At the same time, it is necessary to use a mechanism to monitor the efficiency of the cache (such as event log and performance counter) 1.6 Summary first content briefly introduces the concepts of cache technology, cache data, and programs, advantages, implementation cache schemes, etc. Fundamental contents. 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 the Remoting Singleton cache; use a memory mapped file; use the SQL Server cache; use a static variable cache; use the ASP.NET session state (session state); use ASP. NET client cache and status; use Internet Explorer cache.
2.1 ASP.NET Cache The commonly used data is saved in memory. It is not strange to ASP developers. The session object and Application object provide key value pair to cache data, session object saves and individual users, Application objects Retention and application-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, with the following: 2.1.1 Programming Cache Programmatic CachingCache Object Defines in System.Web.Caching Namespace, you can use the HTTPContext class Cache property or Page object's cache properties to get cache Quote, the Cache object can store objects 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 a cache, you can specify its dependencies to implement it to force to remove it in some cases. The available schemes include the following: • File Dependency - Forced to remove cache data when certain (some) file changes on the hard disk; such as: cachedependency cdependency = newcachedependency (Server.MAppath " .xml ")); cache.insert (" CachedItem ", Item, CDependency); Key Dependency - Removes a data item change in the cache. Such as: // crete a cache entry.cache ["key1"] = "value 1"; // make key2 dependent 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 pre-defined time policies, can be absolute time ( The 18:00 on a date may also be relative time relative now.
Such as: ////////solute expirationcache.insert ("CachedItem", item, null, datetime.now.addseconds (5), cache.noslidingexpiration); /// Sliding expirationcache.insert ("CachedItem", Item, Null, Cache. NoabsoluteExpiration, Timespan.FromSeconds (5)); use too short and too long expiration time, not causing cache data, is buffering old data and has added a cache burden, so you can use high-concurrent testing To determine the optimal 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 to the example of http://www.gotdotnet.com/team/rtoWard. Since the data expires, the data is valid when using data in the cache. As follows: string data = (string) cache ["myitem"]; if (data == null) {data = getdata (); cache.insert ("myitem", data);} DOSMETHINGWITHDATA (DATA); dependency and Expiration Strategy Specifies the way to remove data in the cache, sometimes you may need to do some work when you remove it, this is to rely on the code to achieve this, this is what we have to say. 2.1.1.2 Cache Callback You can define a callback, so that you can not remove it or use new data when you remove it or use new data. 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 expiration 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 into 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 cache entry When using priority 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 ASP The .NET output cache, but there is an alternative method (setting all data failures), such as: response.cache.seXpires (datetime.now) This can clear the cache, but does not reflect it immediately until the initial cache is over, For example: <% @? OutputCache? Duration = "10"? VarybyParam = "none"?%> The specified cache is only 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 You can use the output cache of two ways to cache data-page output caches that need to be transmitted 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 page output cache can cache various information, caching this information means you don't need to process the same data and results, including: • Request but not changed static page • Update the frequency and time known page (such as a page showing the stock price); • According to the http parameters, there are several pages that may be output (such as displaying the city's weather conditions); • From Web Service The result of returning;, such as: [WebMethod (Cacheduration = 60)] public string helloworld () {return "hello world";} 2, cache dynamic pages are often used by input parameters, language, and browser type change dynamic web pages are often used. You can use the following properties of OutputCache to implement a cache for dynamic pages: VaryByParam - multiple versions of the same page based on the input parameters; VarybyHeader - Based on Page Header Different Cache Pages; VarybyCustom - through Declare attributes and overloading the getvarybycustomstring method to customize multiple versions of the cache processing page; VaryByControl - Based on the difference in the ASP object properties in the control to cache controls. The cache for multiple versions will reduce the available memory, so you need to measure the cache policy.
S3, the location of the cache you can use the enumeration value of the @outputcachelocation property to specify the location of the cache, such as: <% @? outputcache? duration = "10"? VarybyParam = "none"? location = "server" ?%> 4, the configuration page output cache has two ways to control, you can use the PAGE instruction, you can also use the Cache API programming. Refer to the following two codes: // code 1, use the instruction <% @? Outputcache? DURATION = "20"? Location = "server"? VarybyParam = "state"? Varybycustom = "minorversion"? VarybyHeader = "accept-language" %> // Code 2, programming 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. Respires (system.datetime.now.ddseconds (20)); // set the header parameter.response.cache.varybyheaders ["accept-language"] = true; // set the cached parameter to 'state' .Response.cache.varybyParams ["state"] = true; // set the customer object .orversion'..response.cache.setvarybycustom ("minorversion"); ...} 2.2.2 Page card breaks Sometimes cache the entire page and Not flexible, while the memory is sent, it is also relatively large, and the interruption cache should be considered at this time. Page card breaks the following types of data: • Create a page break (control) that is overhead; • Page clip containing static data; • Can be used by multiple users; · Multiple pages share page pieces ( Utility Menu Pass) The following is an example of a cache section page: // 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 a non-Web project 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 the Cache object in normal application: 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 procedure running frame. 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 storeprivate Hashtable htStore = new Hashtable (); // Returns a null lifetime manager so that GC will not collect the objectpublic 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 Memory-mapped file provides a unique feature of memory mapping files, allowing applications to access files on disk through pointers - the same way as accessing dynamic compliments. 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. Cache scheme based on memory mapping files contains the following components: • Windows NT Service - Create a memory map 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 mapped file to provide an operation interface; Cache Management DLL - implement specific cache functions, such as: a. Insert and delete data items to the cache; b. Use algorithm clear Cache, such as Least Recently Used; c. Guaranteed data is not tampered; the cache scheme based on memory mapping file can be used in each layer of the application, but because the Win32 API is used, it is not easy to implement. . 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 Using the SQL Server Cache If you need to maintain a cache data in the process of recycling (restart), the machine restart, or the power failure, memory-based schemes 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 to the database with the .NET framework and ADO.Net; • Perfect security models and high robustness; • Data is very convenient; . · Supports a lot of data. · Convenient management tools, there are also shortcomings: • It is necessary to install SQL Server, not suitable for small applications; • Re-constructing the performance of data and the performance comparison of the database; 2.5 Using static variables Cache static variables are often used to record the status 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 using a HashTable implementation: 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 cache session status information for a single user using an ASP.NET Session State based on HTTPSessionState objects.
It solves a lot of restrictions on session status in the ASP, including: • ASP session requires client accepting cookies, otherwise the session can not be used; and ASP.NET can be configured to do not use cookie; • For the Web Server field, ASP SESSSION Can not be supported; when the stability and availability requirements are high, Although the ASP.NET Session State is not good, it is still very effective for smaller single-value Scalar Value (such as login information). ASP.NET session has great improvements, which describes the use and way of use. ASP.NET Session State has three operating modes: 1. Input mode Inproc - session state information stores in memory in the process of ASP.NET work process ASPNET_WP.EXE. 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 proximity mode STATE server-state information is stored 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 sequentially saved in the SQL Server database. You can set the status mode you want to use by adjusting the Mode property of the label in the configuration file, such as using SQL Server mode to share status information in the Web Server field. Of course, this advantage has a shortcoming, that is, status information requires serialization and reverse sequencing, while more writing and reading the database, so there is expenses, which is to be carefully evaluated.
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, it must be guaranteed in the web.config file.
The element is unique on all servers. Such all servers use the same encryption method to access data in the cache. Refer to "MachineKey Elements" in MSDN.
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; 2. If the complex type (such as ArrayList) is selected, only the process is selected. 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 ();
THIS.LBLUSERNAME.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:
this? Frameset? Document? Contains:
Some? neat? contents < / a>
2.7.4 Using cookies
Cookies are another solution that can store data on the client side, but more here.
advantage:
No server resources are required; the data is saved on the client, and is sent to the server when the user request.
Simple to use. Cookie contains simple key value pairs, mainly saving lightweight text data.
Support expired policies; you can specify that the expiration of the session can also specify a time policy.
Disadvantages:
Data amount limit;
Users may be set to reject cookies;
Security problem; users may change the cookie information on the machine, resulting in a cookie-based system operation failed;
It may expire or be deleted by the user, causing a certain degree of unavailability.
See sample code:
Public Class CookiesSample: System.Web.ui.page
{
Private Void Page_Load (Object Sender, System.EventArgs E)
{
IF (this.Request.Cookies ["preferences1"] == null)
{
Httpcookie cookie = new httpcookie ("preferences1");
Cookie.values.Add ("Forecolor", "Black");
Cookie.values.Add ("Backcolor", "beige");
Cookie.values.Add ("Fontsize", "8pt");
Cookie.values.Add ("FontName", "Verdana");
This.Response.AppendCookie (cookie);
}
}
Private string getStyle (String Key)
{
String Val = null;
Httpcookie cookie = this.Request.cookies ["preferences1"];
IF (cookie! = null)
{
Val = cookie.values [key];
}
Return Val;
}
}
2.7.5 Using Query String
Query string is used after the URL requested by the user, can only be used when the URL is called using the HTTP GET method.
advantage:
d. No need server resources, parameters are attached to the URL;
e. Apply surface, almost all browsers are supported;
f. Simple implementation, the server can be read directly from the Request object.
Disadvantages:
a. Parameters can be visible directly to users;
b. URL length limit, most browsers do not support more than 255 characters of URLs.
Sample code:
http://www.cache.com/login.asp?user=ronen
String user = request.queryString ["user"];
2.7.6 small knot
The following table is recommended using the client cache:
Caching mechanism
Applicable
Hidden Field
When the safety requirements are not high, a small amount of data is stored in the page to submit this page or other page on the server.
ViewState
Store a small amount of information to meet the requirements of multiple recovery of the page in a single page. Provide basic security mechanisms.
Hidden Frame
Store data on the client, avoiding the data to the server's backhaul.
Cookie
When the security requirements are not high, a small amount of data is stored on the client.
Query String
A small amount of parameters are transmitted when using the page address connection page.
2.8 Using Internet Explorer cache
IE provides a cache mechanism that enables caches to the page data, and you can specify expiration time. The user requests this page in IE, if the expiration time is not arriving, automatically extract and present from the cache; otherwise, get a new version on the server. IE The cache of the page can be set in IIS.
Suitable content in Internet Explorer
Image file in the page;
Static text content;
The header bar and footer content of the page - the change frequency is very low, and the user can be saved.
Home - Change the number of times the time is relatively small;
Use dynamic HTML to save specific data in the client. For example, customer-defined colors and layout settings information.
advantage:
Reduce requests and network burden on the server;
Support offline browsing;
You can implement XML-based client complex applications.
Disadvantages:
The expiration time of the client must be pre-specified and cannot rely on server updates; IE uses a Lazy update mechanism, and prioritize data from the cache;
There is no effect on other client browsers;
The stored data is not encrypted and cannot guarantee client data security.
Sample code:
3 summary
This document describes the relevant concepts of cache and status data storage, as well as cache technology available to use, describes the scope of the various technologies, and the advantages and disadvantages have been described, and there is a simple performance comparison and simple sample code. . For more information, please refer to the corresponding reference.