Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of caching Technology in .net Environment

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is to share with you the content of sample analysis of caching technology in .net environment. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

I. concept

1.1 problems that caching can solve

Performance-storing the appropriate data to avoid repeated creation, processing, and transmission of the data can effectively improve performance. For example, caching the unchanged data, such as the list of countries, can significantly improve the response speed of web programs.

Stability-it often occurs when multiple requests for the same data, logical function, and user interface are made in the same application. When the user base is very large, if each request is processed, the consumption of resources is a great waste, but also causes the instability of the system. For example, in web applications, caching the content of some static pages can effectively save resources and improve stability. Caching data can also reduce the number of visits to the database, reduce the burden of the database and improve the service ability of the database.

Availability-sometimes, the service that provides data information may stop unexpectedly, and if caching technology is used, it can still provide normal support to end users for a certain period of time, improving the availability of the system.

1.2 understanding status

Before delving into caching technology, you need to have an understanding of state, because caching can be said to be the framework for state management. Understanding the meaning of state and some of its features-such as lifetime and scope-go a long way in deciding whether or not to cache and choosing the appropriate caching technology. State refers to some data, at a certain point in the application system, the state and conditions of the data. The data may be permanently stored in the database, may only stay in memory for a while, or may survive according to a certain logic (such as how long it will take to release), and its scope of application may be accessible to all users. It may be that a single user has permission.

1.2.1 Lifetime of the state

Lifetime refers to the period of time during which data remains valid, that is, the interval from creation to removal. The usual survival periods are as follows:

Persistent data used by a persistent state Permanent State-- application

The process status Process State-- is only valid for the process cycle

Session state Session State-- is related to a specific user session

Message status Message State-- is valid for the time it takes to process a message

1.2.2 range of statu

The scope of a state refers to a physical or logical range that has access to that state.

Physical scope refers to the physical location where state data can be accessed, usually including:

1. All applications of organizational Organization-- in an organization can access status data

2. The field Farm-- can be accessed on any machine within the scope of the application field.

3. Machine Machine-- can be accessed within the scope of a single machine

4. Process Process-- intra-process access permission

5. Application domain AppDomain-- application domain access permission.

Logical scope refers to the logical range of accessible state data. Common ones are:

1. Application Application

2. Business process Business Process

3. Role Role

4. User User

1.2.3 obsolete state data

The cached state data is only a snapshot of the master data (Master State Data), which is stale because the data source may be modified. Making good use of this feature and minimizing the negative impact of obsolete data is an important task of caching state data. You can define the stale basis of the data in the following ways:

Possibility of master data change-does the possibility of master data change greatly increase over time? According to this point, Ann determines the obsolescence of cached state data.

Relevance of changes-when the master data is updated, does the cached state data not update accordingly affect the use of the system? For example, changing the look and feel of the system does not have a significant impact on the business.

1.2.4 tolerance of stale state data

The impact of cache state data obsolescence on business processes is called tolerance. The application system can be No Tolerance and some Tolerance. The former must be updated synchronously with the master data, while the latter allows obsolescence for a certain time or range. The judgment criterion is the impact on the business process.

1.2.5 understand the transition process of state data

Another attribute of state is the form of expression at different stages. What is stored in the database is the data in the original format, the data that has been processed in the business process, and the other form presented to the end user. As shown in the following table:

When deciding to cache data, you should consider which stage (which form) of state data to cache. The following guidelines will help you make a decision:

The original data is cached when the business logic can tolerate the obsolescence of the cached data; the original data can be cached in database access components and service agents

Cache processed data to reduce processing time and resources; processed data can be cached in business logic components and service interfaces.

When the amount of data that needs to be rendered is large and the rendering time of the control is long, cache rendering data (such as a Treeview control that contains a large amount of data). This data should be cached in the UI control.

1.3 Why should data be cached

Caching data in an application has the following benefits:

Reduce interactive traffic-caching data can effectively reduce the amount of transmission between processes and machines

Reduce the amount of processing in the system-reduce the number of processing times

Reduce the number of disk accesses that need to be done-such as data cached in memory.

1.4 where should the data be cached

Cached data is just a copy of the master data, which may be stored in memory or on the hard disk in different forms, that is, as close to the sentence user as possible. So, in addition to considering which data to cache, where the data cache is also a major consideration. This question falls into the following two areas:

1. Physical storage locations available for storage type Storage Type-- data

2. Interlayer schema element (Layered architecture elements)-- the logical storage location where the data can be stored.

1.4.1 Storage Typ

There are many ways to implement caching, all of which can be divided into two categories, memory-based caching and disk-based caching:

1. Memory resident cache-contains all implementations for temporarily storing data in memory, typically used in the following situations:

A) applications frequently use the same data

B) applications need to obtain data frequently

By keeping data in memory, you can effectively reduce expensive disk access operations, and you can also minimize cross-process data transfer by keeping data in user processes.

2. Disk resident caching-this technique includes all caching techniques that use disks as storage media, such as files and databases. Disk-based caching is effective in the following situations:

A) when dealing with large amounts of data

B) the data provided by the application service may not always be available (such as offline)

C) the cached data must remain valid in the event of process recovery and machine restart

By caching processed data, you can effectively reduce the burden of data processing and reduce the cost of data interaction.

1.4.2 Inter-schema elements

The components of each logical layer in the application process data, and when working with these components, you need to consider which data can be cached and how caching will help the overall performance and availability of the program. Of course, there is much more to consider.

1.5 considerations when implementing caching

When designing a caching scheme, you should consider not only which data to cache and where to cache it, but also other factors to consider.

1.5.1 format and access mode

When deciding whether to cache an object, you need to consider three main questions about the format and access mechanism of the data:

1. Thread safety-when the contents of the cache can be accessed by multiple threads, a locking mechanism is used to ensure that the data will not be operated by two threads at the same time.

2. Serialization-when caching an object, you need to serialize it for saving, so the package cached object must support serialization

3. Normalize cached data-when caching data, make sure that the format of the data is optimized relative to the data format to be used.

1.5.2 content loading

Before using cached data, you must load the data into the cache, and there are two mechanisms to load the data:

When you load Proactive Load-- ahead of time, you load all state data into the cache ahead of time, possibly when the application or thread starts, and then caches throughout the lifetime of the application or thread

Dynamic loading Reactive Load--, or reactive loading, when using this method, takes the data when the application requests it and caches it for later use.

1.5.3 expiration policy

Another key factor is how to keep the cached data consistent with the master data (files or databases or other application resources). You can define an expiration policy to determine the contents of the cache, such as when it has been cached or receiving notifications from other resources.

1.5.4 Security

When caching data, you need to be very aware of the potential security threats to the data in the cache. The data in the cache may be accessed or modified by another process, which does not have permissions on the master data. The reason is that when the data is stored in the original location, there is a corresponding security mechanism to protect it, and the same security mechanism is needed when the data is taken out of the traditional security boundary.

1.5.5 Management

When you cache data, the application system needs more maintenance work. When publishing the application, you need to configure the appropriate properties, such as cache size limits and cleanup policies. At the same time, use a mechanism to monitor the efficiency of the cache (such as event logs and performance counters)

2.1 Asp.net cach

Keeping commonly used data in memory is no stranger to asp developers. Session objects and Application objects provide key-value pairs to cache data, Session objects store data related to individual users, and Application objects retain application-related data that every user can access.

In Asp.net, Cache objects are provided specifically for caching data, and its scope of application is the application domain. The lifetime is closely related to the application, recreating the Cache object every time the application starts. The main difference between other domain Application objects is that they provide features specifically for cache management, such as dependency and expiration policies.

You can use the Cache object and its properties for advanced caching, and you can use Asp.net Cache to cache the response output from the client. With regard to caching technology in Asp.net, there are the following:

2.1.1 programming cache Programmatic Caching

The Cache object is defined in the System.Web.Caching namespace. You can use the Cache property of the HttpContext class or the Cache property of the Page object to get a reference to Cache. In addition to storing key-value pairs, the Cache object can also store. Net framework objects. The corresponding dependency and expiration policies are described below.

2.1.1.1 dependency and expiration policy

When you add data to the cache, you can specify its dependencies to force it to be removed in some cases. The available scenarios include the following:

File dependency (File Dependency)-forcibly removes cached data when a file (s) on the hard disk changes; for example:

CacheDependency cDependency = newCacheDependency (Server.MapPath ("authors.xml")); Cache.Insert ("CachedItem", item, cDependency)

Key-value dependency (Key Dependency)-specifies that a data item in the cache is removed when it changes. Such as:

/ / Create 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 policy-invalidates data according to a predefined time policy, either an absolute time (such as 18:00 on a date) or a relative time relative to the present. Such as:

/ / Absolute expirationCache.Insert ("CachedItem", item, null, DateTime.Now.AddSeconds (5), Cache.NoSlidingExpiration); / / Sliding expirationCache.Insert ("CachedItem", item, null, Cache.NoAbsoluteExpiration,TimeSpan.FromSeconds (5))

It is not possible to use either too short or too long expiration time, either resulting in unused cached data or caching stale data and increasing the cache burden, so highly concurrent tests can be used to determine the optimal value of expiration time.

Another problem is how to achieve dependence on the database, which requires the implementation of its own notification mechanism, which can notify you of changes in cached data when the database data changes.

Because the data is out of date, you must check the validity of the data when using the data in the cache. Such as the following code:

String data = (string) Cache ["MyItem"]; if (data = = null) {data = GetData (); Cache.Insert ("MyItem", data);} DoSomeThingWithData (data)

Dependency and expiration policies specify how to remove data from the cache, and sometimes you may need to do some work when the removal occurs, which can be achieved by writing code, which is what we are going to talk about.

2.1.1.2 using cache callback (Cache Callback)

You can define callbacks so that when removal occurs automatically, you don't have to remove it or replace it with 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 priority for cached items

When the server running the application runs out of memory, it automatically clears the data in the cache, called "clear scavenging". At this point, the Cache object determines which cached data is removed first according to the priority of the cached item, and you can specify the priority of the cached item in the 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 way to flush Asp.net 's output cache, but there are alternatives (setting all data to expire), such as:

Response.Cache.SetExpires (DateTime.Now)

This clears the cache, but is not immediately reflected on the page until the end of the initial cache period, such as:

The cache specified by the directive is cleared only after 10 seconds. Usually you don't need to clear all cache entries, all you have to do is reload the data update cache.

2.1.2 output cache (Output Cache)

You can use two ways of output caching to cache the data that needs to be transferred and displayed to the client browser-the page output cache (Page Output Cache) and the page fragment cache (Page Fragment Cache). When the entire page changes relatively little, you can cache the entire page; if only part of the page changes frequently, you can use fragment caching.

2.1.2.1 Page output cache

Page Output Caching caches responses to page requests, and subsequent requests for this page will get information directly from the cache rather than rebuilding the page. This can be achieved by adding Page directives (high-level, declaring implementation) or by using HTTPCachePolicy classes (low-level, program implementation). This guide is not intended to provide technical details, but only guidelines and best practices on how to make better use of it. There are four aspects:

1. Determine the content of the cache

The page output cache caches a variety of information, which means that you don't have to deal with the same data and results often, including:

Static pages that are often requested but not changed

Update a page with a known frequency and time (such as a page showing stock prices)

According to the HTTP parameter, there are several pages that may be output (for example, a page that shows the weather conditions of a city based on its code name)

The result returned from Web Service; for example:

[WebMethod (CacheDuration=60)] public string HelloWorld () {return "HelloWorld";}

2. Cache dynamic pages

Dynamic web pages that change based on input parameters, language, and browser type are often used. You can use the following properties of OutputCache to cache dynamic pages:

VaryByParam-- caches multiple versions of the same page based on different input parameters

VaryByHeader-- multiple versions of different cached pages based on Page Header content

VaryByCustom-- customizes multiple versions of the cache processing page by declaring properties and overloading GetVaryByCustomString methods

VaryByControl-- caches the control based on different properties of the asp object in the control.

Caching multiple versions of pages reduces available memory, so the caching strategy should be carefully measured. S

3. Control the location of the cache

You can use the enumerated value of the OutputCacheLocation property of the @ OutputCache directive to specify the location of the cache, such as:

4. Configure page output cache

There are two ways to control, you can use Page instructions, you can also use Cache API programming. Refer to the following two codes:

/ / Code 1, using instruction / / Code 2, programmatically implements 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.Response.Cache.SetExpires (System.DateTime.Now.AddSeconds (20)); / / Set the Header parameter.Response.Cache.VaryByHeaders ["Accept-Language"] = true;// Set the cached parameter to 'state'.Response.Cache.VaryByParams ["state"] = true / / Set the custom parameter to 'minorversion'.Response.Cache.SetVaryByCustom ("minorversion"); … }

2.1.2.2 Page fragment cache

Sometimes caching the entire page is not flexible, and memory is also large, so fragment caching should be considered. Page fragment caching is suitable for the following types of data:

Create expensive page fragments (controls)

Page fragments containing static data

Page fragments that can be used by multiple users

A page fragment shared by multiple pages (such as a common menu bar)

The following is an example of caching some pages:

/ / Partial caching for 120seconds [System.Web.UI.PartialCaching] public class WebUserControl: System.Web.UI.UserControl {/ / Your Web control code}

2.1.3 using Asp.net caching in non-Web projects

Asp.net Cache is located in the System.Web namespace, but because it is a common schema, you can still use it in any non-Web project that references this namespace.

The System.Web.Caching.Cache class is a cache of objects that can be accessed through the static properties of System.Web.HttpRuntime.Cache or through System.Web.UI.Page and System.Web.HttpContext.Cache. Therefore, it can also exist outside the request context, and there is only one instance in each application domain, so the HttpRuntime.Cache object can exist in each application domain outside the Aspnet_wp.exe. The following code demonstrates accessing Cache objects in a normal application:

HttpRuntime httpRT = new HttpRuntime ()

Cache cache = HttpRuntime.Cache

2.2 use Remoting Singleton caching

.net Remoting provides a framework for running programs across application domains, processes, and computers. There are two activation modes for server-activated objects, of which the Singleton type does not have multiple instances at any time. If an instance exists, all client requests are serviced by that instance. If no instance exists, the server will create an instance and all subsequent client requests will be serviced by that instance. Because the Singleton type has an associated default lifetime, the client does not always receive a reference to the same instance of a remotable class, even if there is no more than one instance available at any time. So caching data allows you to share status information among multiple clients.

In order to implement the caching scheme using .net Remoting, ensure that the lease of the remote object does not expire and that the remote object is not destroyed by the garbage collector (object lease is the lifetime of the object in memory before the system deletes it). When caching is implemented, the InitializeLifetimeService method of MarshalByRefObject is overloaded and null is returned, which ensures that the lease never expires and the associated object lifetime 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 won't collect the objectpublic override object InitializeLifetimeService () {return null;} / / Your custom cache interface}

Note: due to the high cost, performance limitations and possible system instability, the Sql Server-based scheme is usually used instead.

2.3 use memory-mapped files (Memory-Mapped File)

Memory-mapped files provide unique features that allow applications to access files on disk through pointers-in the same way as dynamic memory. So you can map the data of an address segment in the application process to a file for multiple cross-application domain or cross-process access.

In windows, code and data are processed in a way that takes the form of memory pages, while behind memory pages are files on disk. The only file types on different disks are different. The executable image is behind the code, and the page file of the system is behind the data. When multiple applications share memory, the performance of the system is significantly improved.

You can use this feature of memory-mapped files to implement caching solutions across processes and application domains on the same machine. The caching scheme based on memory-mapped files consists of the following components:

Windows NT service-creates a memory-mapped file at startup and deletes it when stopped. The function is to provide a handle to a process that uses the cache. Of course, you can also use a named memory mapping file to provide an operation interface

Caching managed component (Cache Management Dll)-implements specific caching functions, such as:

a. Insert and delete data items into the cache

b. Use an algorithm to clear the cache, such as finally using an algorithm (Least Recently Used)

c. Ensure that the data will not be tampered with.

The caching scheme based on memory-mapped files can be used in every layer of the application, but it is not easy to implement because of the use of win32 API calls. The .net framework does not support memory-mapped files, so it can only be run in unmanaged code, and certainly cannot take advantage of the powerful features of the .net framework, such as garbage collection. At the same time, the management function of cached data items needs to be customized, and performance counters should be developed to monitor the effect of caching.

2.4 using SQL Server caching

If you need to keep the cached data valid during process recovery (restart), machine restart, or power failure, the memory-based solution does not meet the requirements. You can use a solution based on permanent data storage, such as a SQL server database or a NTFS file system.

When SQL Server uses SQL statements or stored procedures to get data, there is an 8k size limit for data of varchar and varBinary types. You must use the Ado.Net SQLDataAdapter object provided by the .net framework to access datatable or dataset.

Advantages of using SQL Server to cache data:

Easy to implement-it is quite convenient to access the database using the .net framework and Ado.Net

Perfect security model and high robustness

Data sharing is very convenient.

Persistent retention of data.

Support a large amount of data.

Convenient management tools

Of course, there are drawbacks:

SQL Server needs to be installed, which is not suitable for small applications

Performance comparison between reconstructing data and reading database

Network burden.

2.5 use static variable caching

Static variables are often used to record the state of a class, and you can use it to create custom cache objects. Declare your data store as static variables in a custom cache class and provide maintenance interfaces (insert, delete, access, etc.). If there are no special caching requirements (such as dependencies, invalidation strategies, etc.), it is convenient to use static variables to cache data. Because it is in memory, this scheme can provide direct, high-speed access to cached data, and static variables can be used when there is no alternative solution to the storage of key-value pairs and high speed is required. Of course, in asp.net, you should use the Cache object.

You can use this scheme to save big data's object, as long as it doesn't change very often. Because there is no clearing mechanism, big data's memory consumption will affect performance.

You need to ensure a custom thread-safe mechanism, or use synchronization objects provided by the .net framework, such as Hashtable. The following code is an example of an implementation using Hashtable:

Static Hashtable mCacheData = new Hashtable ()

Scope of application: the scope of application of this scheme can be limited to classes, modules or the whole project. If the variable is defined as public, the code throughout the project can access it, and the scope is the entire application domain, achieving efficient sharing. And its lifetime is closely related to the scope.

2.6 use asp.net session state

You can use asp.net session state based on HttpSessionState objects to cache session state information for individual users. It addresses many of the restrictions on session state in asp, including:

Asp session requires the client to accept cookies, otherwise session; cannot be used and asp.net can be configured not to use cookie

In the case of web server farms, asp's session is not supported; when stability and availability are high, asp.net session state is not effective, but it is still effective for relatively small single-value scalar Value (such as login information).

Asp.net session has been greatly improved. The scope of use and how to use it are described below.

Asp.net session state has three modes of operation:

1. The InProc--Session State information of intra-process mode is stored in the memory of the process of asp.net worker process aspnet_wp.exe. This is the default option, in which case, if the process or application domain is recycled, the Session status information is also recycled

2. The out-of-process mode State Server-- state information is serialized and saved in a separate state process (AspNet_State.exe), so the state information can be saved on a dedicated server (a state server State Server).

3. Sql server mode-the state information is serialized and saved in the SQL Server database.

You can set the state mode to use by adjusting the mode attribute of the tag in the configuration file, such as using SQL Server mode to share state information in the Web server field. Of course, this advantage also has the disadvantage that the state information needs to be serialized and deserialized, while there are more writes and reads to the database, so there is an overhead in performance, which needs to be carefully evaluated.

2.6.1 Select usage mode

2.6.1.1 using InProc mode

When using in-process mode, the state information is saved in the process of aspnet_wp.exe. Because multiple instances of aspnet_wp.exe are running on the same server in the case of a web farm, the in-process mode is not suitable for the case of a web farm.

In-process mode is the only session mode that supports Session_End events, and when a user's session times out or aborts, you can run the event handling code in Session_End to clear resources.

2.6.1.2 using StateServer mode

The StateServer mode stores state information using the specified process. Because it is also an out-of-process mode, make sure that the objects you store are serializable to support cross-process transfer.

When using Session objects in the case of a web farm, you must ensure that the elements in the web.config file are unique on all servers. In this way, all servers use the same encryption method in order to access the data in the cache. Refer to the "MachineKey element" in msdn.

2.6.1.3 using SQL Server mode

In SQL Server mode, when you access Session state information using a trusted connection (trusted_connection=true or integrated security=sspi), you cannot use identity user impersonation in asp.net.

By default, SQL Server stores state information in the TempDb database, which is automatically recreated every time the Sql server service starts. Of course, you can specify your own database to keep the data during the database restart.

2.6.2 decide what to store using the Session object

You can use Session objects to cache any type of. Net framework data, but understand what is the best way for a certain type. The following points need to be explained:

1. For basic types (such as Int,Byte,String), you can use any method. Because when choosing an out-of-process approach, asp.net uses an optimized internal method to serialize and deserialize basic types of data

2. For complex types (such as ArrayList), only the in-process approach is selected. Because asp.net uses BinaryFormatter to serialize and deserialize this kind of data, which can affect performance. Of course, serialization operations are performed only in State Server and SQL Server mode

3. The security of the cache. When storing sensitive data in the cache, security needs to be considered. Other pages can access the data in the cache.

4. Avoid caching big data, which will degrade performance

5. This caching method does not support expiration policy, cleanup and dependency.

2.6.3 implement Session State

Asp.net provides a simple interface to operate Session State, and you can use Web.Config to make simple settings, which can be immediately reflected on the page when the settings in the configuration file change, without the need to restart the asp.net process.

The following code demonstrates the use of SQL Server to store and use Session data.

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 using Asp.net client caching and status

You can also use the client to store page information to reduce the burden on the server, which provides the lowest security, but has the fastest performance. The amount of data is limited because it needs to be sent to the client for storage.

There are five mechanisms to implement client-side caching, which will be described in turn:

Hidden field (Hidden Field)

View State

Hidden frame (Hidden Frame)

Cookies

Query String

These five methods are suitable for storing different types of data.

2.7.1 using Hidden Field

You can save a small amount of data that changes frequently in HtmlInputHidden to maintain the state of the page. When each page is sent back, the data will be included in the form and sent to the server, so you need to use HTTP POST to submit the page.

The advantages of using this approach are as follows:

Do not need server resources, read directly from the page

Almost all browsers support it.

Easy to implement

Because the data is on the page, it can also be used in the case of web Farm.

Disadvantages:

Because it can be seen by looking at the source code, it may be tampered with

Complex format data is not supported, and complex data must be obtained indirectly by parsing strings.

When storing big data, it will affect performance.

Example:

2.7.2 using View State

All Web Form pages and controls contain a ViewState property that maintains the value within the page when multiple requests are made to the same page. Its internal implementation is to maintain the corresponding hidden field, but it is encrypted, so it is more secure than hidden field.

Performance with View State depends largely on the type of server control. In general, the performance of Label,TextBox,CheckBox,RadioButton,HyperLink is better, while DropdownList,ListBox,DataGrid and DataList are much worse because it contains so much data that it takes time to send back each page.

ViewState is not recommended in some cases, such as:

1. Avoid using pages that do not need to be sent back

2. Avoid using ViewState to save a large amount of data

3. Avoid using it when you need to use a session timeout, as it does not have a timeout.

The performance of ViewState is similar to that of Hidden Field, but with higher security.

Advantages:

Data is automatically maintained on the page and does not require server resources

Easy to implement

The data is encrypted and compressed and has higher security than hidden field

The data is stored on the client and can be used in the case of Web Farm.

Disadvantages:

Performance degrades when storing large amounts of data

Like hidden field, there are still potential security threats to client-side 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 on the client side, which avoids cached data round trips each time a page is sent back using hidden field and view state. For example, you can secretly load images needed by multiple pages, which does not consume server resources.

Advantages:

a. You can load more data than just the values of a single field

b. Avoid unnecessary data exchanges in multiple echoes

c. You can cache and read data items stored in different forms (you can cache data from multiple pages at the same time)

d. You can access client script data in different frame of the same site.

Disadvantages:

a. Some browsers do not support frame

b. The source code can be seen on the client side, and there are potential security threats

c. There is no limit to the number of hidden frame, and if the frame page contains more hidden frame, there will be a speed limit when loading for the first time.

The sample code is as follows:

This frameset document contains:Some neat contents

2.7.4 using Cookies

Cookie is another way to store data on the client side, which is not covered here.

Advantages:

No server resources are required; the data is saved on the client and sent to the server when requested by the user.

Easy to use. Cookie contains simple key-value pairs, mainly storing lightweight text data.

Support expiration policy; you can specify expiration at the end of the session, or you can specify a time policy.

Disadvantages:

Limitation of the amount of data

The user may be set to reject Cookie

Security problems; users may change the cookie information on the machine, causing the cookie-based system to fail

It may expire or be deleted by the user, resulting in a certain degree of unavailability.

See the 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 by adding the corresponding parameters to the URL requested by the user, and is only available when calling URL in HTTP GET mode.

Advantages:

d. Server resources are not required. Parameters are attached to URL.

e. It has a wide range of applications and almost all browsers support it.

f. The implementation is simple, and the server can read it directly using the Request object.

Disadvantages:

a. The parameter is directly visible to the user and is not safe

Due to the limit of b.URL length, most browsers do not support URL with more than 255characters.

Sample code:

String user = Request.QueryString ["User"]

2.7.6 Summary

The following table is recommended for using client-side caching:

2.8Use Internet Explorer caching

IE provides a caching mechanism to cache the data of the page and specify the expiration time. The user requests this page in IE, and if the expiration time is not up, it is automatically extracted from the cache and rendered; otherwise, the new version is obtained on the server. IE's cache of pages can be set in IIS.

Content suitable for caching in Internet Explorer

Image files in the pa

Static text content

Page title bar and footer content-change frequency is very low, can give the user a quick response

The home page of a website-the number of changes to the page is relatively small

Use dynamic HTML to save specific data on the client, such as customer-customized color and layout setting information.

Advantages:

Reduce the request and network burden on the server

Support offline browsing

Complex client applications based on XML can be realized.

Disadvantages:

The expiration time of the client must be specified in advance and cannot be dependent on the server update; IE uses the Lazy update mechanism and gives priority to extracting data from the cache

Has no effect on other client browsers

The stored data is not encrypted, which can not guarantee the security of the client data.

Sample code:

Thank you for reading! This is the end of this article on "sample analysis of caching technology in .net environment". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report