Asp.net Program Performance Optimization

Source: Internet
Author: User

I. Database Operations

1. Close the database connection immediately after use

To access database resources, you need to create a connection, open a connection, and close the connection. These processes need to exchange information with the database multiple times to pass identity authentication, which consumes server resources.

Source. ASP. NET provides a connection pool to improve the impact of enabling and disabling databases on performance. The system places the user's database connection in the connection pool. If necessary, the connection is taken out. When the connection is closed, the connection is withdrawn and the next connection request is waited.

The size of the connection pool is limited. If you still need to create a connection after the connection pool reaches the maximum limit, the performance will be greatly affected. Therefore, after a database connection is established, the connection is enabled only when operations are required. The connection is closed immediately after use, so as to minimize the time for opening the database connection and avoid exceeding the connection limit.

Usage (recommended)
Using (sqlconnection conn = new sqlconnection (connstr ))
{} // Do not show off

Or
Try {conn. open ();}
Catch {}
Finally {conn. Close ();}

2. Use stored procedures whenever possible and Optimize Query statements

Stored procedures are a set of pre-compiled SQL statements stored on the server, similar to the batch processing files in the DOS system. Stored Procedures provide the ability to access databases immediately and process information quickly. Using the stored procedure can avoid multiple compilation of commands. After one execution, the execution plan will reside in the cache. In the future, you only need to directly call the binary code in the cache. Among all data access methods provided by. NET Framework, SQL Server-based data access is a recommended choice for generating high-performance, scalable Web applications. When using a hosted SQL Server Provider, you can use compiled stored procedures instead of special queries to obtain additional performance improvements.

In addition, the stored procedure runs on the server and is independent from the ASP. Net program to facilitate modification. The most important thing is that it can reduce the transmission of database operation statements over the network.

Optimize Query statements

In ASP. NET, the ADO connection consumes a considerable amount of resources. The longer the SQL statement runs, the longer the system resources are occupied. Therefore, try to use optimized SQL statements to reduce execution time. For example, if a query statement does not contain a subquery statement, only useful data and fields should be returned as much as possible to make full use of indexes.

3. Use sqldatareader for read-only data access. Do not use dataset.

The sqldatareader class provides a method for reading data streams only retrieved from the SQL Server database. If you are allowed to use an ASP. NET application when creating it, The sqldatareader class provides higher performance than the dataset class. This is because sqldatareader uses the Local Network Data Transmission Format of SQL Server to directly read data from the database connection. In addition, the sqldatareader class implements the ienumerable interface, which allows you to bind data to server controls. As a powerful and offline database, dataset has a relatively high performance cost.

Sqldataread advantages: fast data reading. If you do not need to process the returned data in large quantities, we recommend that you use sqldatareader. Its performance is much better than that of datset. Disadvantage: the connection to the database cannot be closed until the data is read.

Dataset reads data and caches it in the memory. Disadvantage: High memory usage. If a large amount of processing is required for the returned data, it is better to use dataset to reduce the connection operations to the database. Advantage: Only one connection is required to close the connection to the database.

Generally, sqldatareader is used to read a large amount of data and not process the returned data in large quantities. It is more appropriate to use datset to process a large amount of returned data. The selection of sqldatareader and dataset depends on the implementation of program functions.

4. Data Binding databinder

General Binding method <% # databinder. eval (container. dataitem, "field name") %>

Binding with databinder. Eval does not require concern about the data source (read or dataset ). The data type Eval will convert the data object into a string. It does a lot of work on the underlying binding and uses the reflection performance. This is because it is easy to use, but affects data performance.

Let's see <% # databinder. eval (container. dataitem, "field name") %>. When dataset is bound, dataitem is actually a datarowview (if it is bound to a data reader (dataread), it is an idatarecord .) Therefore, directly converting to datarowview will greatly improve the performance.

<% # Ctype (container. dataitem, datarowview). Row ("field name") %>

We recommend that you use <% # ctype (container. dataitem, datarowview). Row ("field name") %> to bind data. Pay attention to the following two aspects during use:
1. Add <% @ import namespace = "system. Data" %>.
2. Pay attention to the Case sensitivity of field names ). If it is inconsistent with the query, it may be slower than <% # databinder. eval (container. dataitem, "field name") %> in some cases. To further increase the speed, you can use the <% # ctype (container. dataitem, datarowview). Row (0) %> method. But its readability is not high.

The above is the VB.net method. In C #: <% # (datarowview) container. dataitem) ["field name"] %>

5. Multiple result sets are returned.

Whether sqldatareader or datset, multiple result sets are returned. Then, RD. nextresult () or ds. Tables [I] is used to process the data separately, reducing the number of times the database is reconnected. At the same time, try to replace complicated dataset secondary processing with more efficient SQL statements.

Ii. Page Optimization

1. Unnecessary Server Control)

In Asp.net, a large number of server-side controls facilitate program development, but may also lead to performance loss, because each time a user operates a server-side control, a round-trip process with the server is generated. Therefore, server control should be used less unless necessary. In many other cases, rendering or data binding is more effective than using server controls, even when using server control templates. However, if you want to programmatically manipulate the properties of the server control, process server control events, or save the view status, use the server control as appropriate.

Therefore, select the HTML control whenever possible. Functions that can be implemented on the client are implemented on the client (proficient in Javascript) to reduce the pressure on the server.

2. Do not use unnecessary viewstate

By default, ASP. NET enables viewstate (view State) for all server control ). However, viewstate needs to save some information on the client, which may cause performance consumption. If you must use server control, you can disable viewstate.
Only save the Server Control view status when necessary. Automatic view status management is a function of the server control. This function enables the Server Control to re-fill their attribute values during the round-trip process (you do not need to write any code ). However, because the view status of the server control is redirected to and from the server in the hidden form field, this function does have an impact on performance. You should know under which circumstances the view status will be helpful and under which circumstances it will affect the page performance. For example, if you bind a server control to data during each round-trip process, the new value obtained from the data binding operation replaces the saved view status. In this case, disabling the view status can save processing time.

By default, view status is enabled for all server controls. To disable view status, set the enableviewstate attribute of the control to false, as shown in the following DataGrid Server Control example.

<Asp: DataGrid enableviewstate = "false" runat = "server"/>
You can also use the @ page command to disable the view status of the entire page. This is useful when you do not send a page back to the server: <% @ page enableviewstate = "false" %>

Note that the @ control command also supports the enableviewstate attribute, which allows you to control whether the view State is enabled for the user control.
To analyze the number of view States used by the server control on the page, please (include the trace = "true" attribute in the @ page command) enable tracing on this page and view the viewstate column of the control hierarchy table.

3. Avoid unnecessary round-trip to the server

Although you may want to use the time-saving and code-saving functions of the web forms page framework as much as possible, ASP. NET Server controls and sending back events cannot be used in some cases.

Generally, you only need to start the round-trip process to the server when retrieving or storing data. Most data operations can be performed on clients during the round-trip process. For example, it is often possible to verify user input from an HTML form on the client before the data is submitted to the server. Generally, if you do not need to pass the information to the server to store it in the database, you should not write the code that leads to the round-trip process.

If you develop custom server controls, consider making them present client code for browsers that support ecmascript. By using the server control in this way, you can significantly reduce the number of times information is not necessary to be sent to the web server.

Use Page. ispostback to avoid unnecessary operations on the round-trip Process

If you write the code for processing the Server Control sending and processing, you may sometimes need to execute other code on the first request page, instead of the Code executed when the user sends an HTML form contained in the page. Use the page. ispostback attribute to execute code conditionally based on whether the page is generated in response to the server control event. For example, the following code demonstrates how to create a database connection and command. This command binds data to the DataGrid server control when you request this page for the first time.

Void page_load (Object sender, eventargs E)
{
If (! Page. ispostback)
{}
}

Because the page_load event is executed during each request, the code above checks whether the ispostback attribute is set to false. If yes, the code is executed. If this attribute is set to true, no code is executed.

Note that if you do not run this check, the page sending behavior will not be changed. The code of the page_load event is executed before the Server Control event is executed, but only the results of the server control event can be displayed on the output page. If you do not run this check, the page_load event and any server control event on the page will still be processed.

4. Disable the session when the session status is not used, and use as few sessions as possible during program development.

Not all applications or pages need to be specific to the user's session status. You should disable the session status for any applications or pages that do not need the session status.

To disable the page session Status, set the enablesessionstate attribute in the @ page command to false. Example: <% @ page enablesessionstate = "false" %>

Note: If the page needs to access session variables without creating or modifying them, set the enablesessionstate attribute in the @ page command to readonly.

To disable the session Status of an application, set the mode attribute to off in the sessionstate configuration section of the Application Web. config file. Example: <sessionstate mode = "off"/>

5. Use the DataGrid properly (in ASP. net2.0, The gridview Control)

The DataGrid Control has the most powerful data display function and has many built-in functions such as data modification, deletion, addition, and paging. If you only need to simply display the data, the DataGrid is not the best choice. The paging function and data storage method of the DataGrid Control (stored in viewstate) make it easy and convenient for program developers to use, but the resulting performance overhead is not negligible.

The datalist control has much fewer functions than the DataGrid Control. However, the customization is much stronger. The unique multi-row data display is more convenient. The functions that the DataGrid can implement.

The Repeater control has the least functions, but is very user-defined. Due to the reduction of many functions, the performance of the server is minimized.

Therefore, when you simply need to display the data list, you can select the repeater or datalist control to achieve the same purpose and reduce the performance overhead.

Recommended sequence: repeater and datalist last DataGrid (gridview)

6. Paging data

The ASP. NET DataGrid (in ASP. net2.0, The gridview) has a very useful function: paging. If the DataGrid allows paging, it only downloads data on a certain page at a certain time. In addition, it has a data paging navigation bar, which allows you to choose to browse a certain page, in addition, only one page of data is downloaded at a time.

But it has a small drawback: You must bind all the data to the DataGrid. That is to say, your data layer must return all the data, and the DataGrid then filters out the data needed for the current page based on the current page. If there is a result set with 10 thousand records to be paged using the DataGrid, assuming that only 25 data entries are displayed on each page of the DataGrid, it means that 9975 data entries are discarded in each request. Each request must return such a large dataset, which has a very high impact on the performance of the application.

A good solution is to write a paging storage process,
For example:

Create procedure DBO. sp_datapages
@ SQL nvarchar (2000 ),
@ PK varchar (50), -- primary key field name (can be of any data type; no, and no table name prefix is required, such as: cannot be users. ID)
@ Order varchar (50), -- sorting method (with DESC or ASC, it can be multiple combinations; no, and the table name prefix is not required. For example, it cannot be users. id DESC)
@ Page int,
@ Pagesize Int = 30
As

Set nocount on

Declare @ STR nvarchar (4000)

If (@ page = 1)
Set @ STR = 'select top '+ Cast (@ pagesize) as varchar (20) +' * from ('+ @ SQL + ') as Table1 order by table1. '+ @ order
Else
Set @ STR = 'select top '+ Cast (@ pagesize) as varchar (20) +' * from ('+ @ SQL + ') as Table1 where table1. '+ @ PK +' not in (select top '+ Cast (@ pagesize * (@ page-1) as varchar (20 )) + ''+ @ PK + 'from (' + @ SQL + ') as Table2 order by table2.' + @ order + ') order by table1.' + @ order

-- Print @ Str
-- Exec (@ Str)
Exec sp_executesql @ Str

Set nocount off

Go

Alternatively, use the row_number () function in SQL Server 2005.

Declare @ SQL varchar (8000)

Set @ SQL = 'select *'
+ 'From'
+ '('

+ 'Select row_number () over (order by id desc) as rownumber ,*'
+ 'From users'
+ 'Where ID> 0 and name <> '''''

+ ')'
+ 'As table1'

+ 'Where rownumber between' + STR (@ page-1) * @ pagesize + 1) + 'and' + STR (@ page * @ pagesize)
+ 'Order by id desc'

-- Exec (@ SQL)
Exec sp_executesql @ SQL

(TIPS: Keep the total number of records as cache or session to improve paging performance .)

7. Do not disable Web form page buffering.

Disable the buffer unless otherwise specified. Disabling web form page buffering can cause a large amount of performance overhead.

Enable the buffer for page output)
If the buffer mechanism is disabled, use the following method.
Use a program to open the page output cache:
Response. bufferoutput = true;

Use the @ page switch to enable the page output buffer mechanism:
<% @ Page buffer = "true" %>

Use the <pages> node of the web. config or machine. config configuration file:
<Pages buffer = "true"/>

8. Set the smart navigation attribute of the page.

Setting SMART navigation to true can significantly improve user performance. Enabling this attribute has little impact on the client and server. It can intelligently refresh what needs to be refreshed.

In most cases, do not set this attribute in code.
Set the smartnavigation attribute to true in the @ page command of the. aspx file. When you request this page, the dynamically generated class sets this attribute.

When a browser requests a page (or later) in Internet Explorer 5 or later, intelligent navigation improves the user's ability to operate the page by executing the following functions:
Eliminate flickering caused by navigation.
Keep the scroll position when you move from one page to another.
Maintain the element focus between navigation.
Only the status of the last page is retained in the browser history.

Intelligent Navigation is most suitable for ASP. NET pages that require frequent sending back, but their content does not change significantly when it is returned. Consider this carefully when deciding whether to set this attribute to true.

C # (or VB.net) Program Improvement

1. Use the tostring method of Value Type

When connecting strings, you often use the "+" sign to directly add numbers to strings. This method is simple and can get the correct results. However, because different data types are involved, the numbers must be converted to the reference type through the boxing operation before they can be added to the string. However, the packing operation has a great impact on the performance, because during such processing, a new object will be allocated in the managed heap, and the original value will be copied to the newly created object.

The Value Type tostring method can be used to avoid packing and improve application performance.

Int num = 1;
String STR = "go" + num. tostring ();

2. Use the stringbuilder class

The string class object cannot be changed. In essence, the re-assignment of the string object re-creates a String object and assigns the new value to the object, the tostring method does not significantly improve the performance.

When processing strings, it is best to use the stringbuilder class. Its. Net namespace is system. Text. This class does not create a new object, but directly performs operations on strings through append, remove, insert, and other methods, and returns the operation results through the tostring method.

Its definition and operation statement are as follows:

Int num;

System. Text. stringbuilder STR = new system. Text. stringbuilder (); // create a string

Str. append (Num. tostring (); // Add the numeric value num

Response. Write (Str. tostring); // display the operation result

3. Use httpserverutility. Transfer to redirect between pages of the same application

Use the server. transfer syntax to avoid unnecessary client redirection (response. Redirect) by using this method on the page ).

4. Avoid using arraylist.

Because any object to be added to the arraylist must be of the system. Object type. When retrieving data from the arraylist, it must be split back to the actual type. We recommend that you replace arraylist with a custom set type. Asp.net 2.0 provides a new type called generic, which is a strong type. Using a generic set can avoid the occurrence of binning and unpacking and improve the performance.

5. Use hashtale to replace other dictionary set types
(Such as stringdictionary, namevaluecollection, and hybridcollection). hashtable can be used to store a small amount of data.

6. Declare constants for string containers. Do not enclose the characters in double quotation marks.
// Avoid
Myobject OBJ = new myobject ();
OBJ. Status = "active ";

// Recommended
Const string c_status = "active ";
Myobject OBJ = new myobject ();
OBJ. Status = c_status;

7. Do not use toupper () or tolower () to convert strings for comparison. Use string. Compare instead. It can be case-insensitive for comparison.
Example:
Const string c_value = "Compare ";
If (string. Compare (svariable, c_value, true) = 0)
{
Console. Write ("same ");
}
You can also use STR = string. Empty or str. Length = 0 to determine whether it is null. (Check the length of the input data to prevent SQL injection attacks)
Comparing the Length attribute of a string object with 0 is the fastest way to avoid unnecessary calls to the toupper or tolower method.

8. type conversion int32.tryparse () is superior to int32.parse () and convert. toint32 ().

We recommend that you use int32.parse () in. net1.1 and int32.tryparse () in. net2.0 ().
Because:
Convert. toint32 will delegate the final parsing work to int32.parse;
Int32.parse will delegate the final parsing work to number. parseint32;
Int32.tryparse will delegate the final parsing work to number. tryparseint32.

9. If you only want to read data from an XML object, replacing xmldocument with a read-only xpathdocument can improve the performance.

// Avoid
Xmldocument xmld = new xmldocument ();
Xmld. loadxml (sxml );
Txtname. Text = xmld. selectsinglenode ("/packet/child"). innertext;

// Recommended
Xpathdocument xmldcontext = new xpathdocument (New stringreader (ocontext. Value ));
Xpathnavigator xnav = xmldcontext. createnavigator ();
Xpathnodeiterator xpnodeiter = xnav. Select ("packet/child ");
Icount = xpnodeiter. count;
Xpnodeiter = xnav. selectdescendants (xpathnodetype. element, false );
While (xpnodeiter. movenext ())
{
Scurrvalues + = xpnodeiter. Current. Value + ",";
}

10. Avoid declaring variables in the cyclic body. Declare variables in the circulating body and initialize them in the cyclic body.

C # A basic principle for program development is to avoid unnecessary object creation.

// Avoid
For (INT I = 0; I <10; I ++)
{
Someclass objsc = new someclass ();
}

// Recommended
Someclass objsc = NULL;
For (INT I = 0; I <10; I ++)
{
Objsc = new someclass ();
}

11. Catch the specified exception. Do not use general system. Exception.

// Avoid
Try
{
<Some logic>
}
Catch (exception exc)
{
<Error handling>
}

// Recommended
Try
{
<Some logic>
}
Catch (system. nullreferenceexception exc)
{
<Error handling>
}
Catch (system. argumentoutofrangeexception exc)
{
<Error handling>
}
Catch (system. invalidcastexception exc)
{
<Error handling>
}

12. When using try... catch... finally, you must release the resources occupied in finally, such as connections and file streams.
Otherwise, the resources occupied after an error is caught cannot be released.

Try
{}
Catch
{}
Finally
{
Conntion. Close ();
}

13. Do not use exception to control program processes
Some programmers may use exceptions to implement some process control. For example:

Try {
Result = 100/num;
}
Catch (exception E)
{
Result = 0;
}

However, exceptions consume a lot of system performance. Unless necessary, exception control should not be used to implement the program process. The above code should be written as follows:

If (num! = 0)
Result = 100/num;
Else
Result = 0;

14. Avoid using recursive calls and nested loops. Using them will seriously affect performance and will be used only when you have to use them.

15. Disable the Dynamic Data Types of VB.net and JScript.

The variable data type should always be explicitly stated, which can save the execution time of the program. In the past, one of the reasons why developers like to use Visual Basic, VBScript, and JScript was their so-called "non-typed" nature. Variables do not need explicit type declarations and can be created simply by using them. When the data is allocated from one type to another, the conversion is automatically executed. However, this convenience will greatly damage the performance of the application.
For example:
To achieve optimal performance, assign a type to the JScript. Net variable when declaring it. For example, var a: string;

Iv. Use Cache

1. Use output cache to cache data

The cache feature is a very powerful feature in Asp.net. I have seen some evaluations that the performance of the Asp.net program is several times faster than that of Sun's JSP application. In fact, a very important aspect of this evaluation program is the use of many Asp.net cache functions.

If your component is to run in the Asp.net application, you just need to reference system. Web. DLL to your project. Then, use the httpruntime. cache attribute to access the cache (you can also access the cache through page. cache or httpcontext. cache ).

There are several rules for caching data. First, data may be frequently used and can be cached. Second, the Access frequency of data is very high, or the access frequency of a data is not high, but it has a long life cycle, so it is best to cache such data. The third is a problem that is often ignored. Sometimes we cache too much data, usually on an x86 host. If you want to cache more than MB of data, A memory overflow error occurs. Therefore, the cache is limited. In other words, you should estimate the size of the cache set and limit the size of the cache set to less than 10; otherwise, problems may occur. In Asp.net, if the cache is too large, a memory overflow error is reported, especially when the DataSet object is large.

There are several important caching mechanisms that you must understand. First, the cache implements the "recently used" principle (a least-recently-used algorithm). When the cache is small, it will automatically force the useless cache to be cleared. Next, the "Conditional dependency" principle is enforced (expiration dependencies). The condition can be time, keyword, and file. Time is the most common condition. Add a stronger condition in ASP. net2.0, that is, the database condition. When the data in the database changes, the cache is forcibly cleared.

There are two points to note when using the ASP. NET cache mechanism. First, do not cache too many items. Each item in the cache has an overhead, especially for memory usage. Do not cache items that are easy to recalculate and rarely used. Second, the period of validity allocated to cached items should not be too short. Items that expire soon will result in unnecessary turnover in the cache, and often lead to more code cleanup and garbage collection work. If you are concerned about this issue, monitor the cache total turnover rate performance counters associated with ASP. NET applications performance objects. High turnover rate may indicate problems, especially when items are removed before expiration. This is also called memory pressure.

Remember:

Should:
Data that is frequently accessed and infrequently changed should be cached.
The settings or objects used by the entire application should be cached, but these settings and objects must not change during their lifetime.
Should not:
Do not cache personal information. If personal information is cached, it is easy for others to obtain this information.
Do not cache pages that contain time values. Otherwise, the browser cannot understand why time is always lagging.
Do not cache objects that users can modify at any time, such as shopping cart.

Common cache methods in Asp.net include:

1) page cache (cache the entire page)

<% // Response. addheader ("last-modified", datetime. Now. addhours (-1). tostring ("R"); %>
<% Response. addheader ("cache-control", "Max-age = 86400"); %>
<% // Response. addheader ("date", datetime. Now. addminutes (-59). tostring ("R"); %>

<% @ Page outputcache varybyparams = "classid; Page" duration = "3600" %>

For. net2.0:
<% @ Outputcache varybyparam = "classid; Page" duration = "3600" %>

You can use the page output cache content generated in the first request to generate a new page content in 3600 seconds. This technology is actually implemented using some low-layer cache APIs. Several parameters can be configured in the page output cache. As mentioned above, the varybyparams parameter indicates when to trigger the re-output condition, you can also specify the cache output in http get or http post request mode.

For example, when we set this parameter to varybyparams = "classid; page", default. aspx? The output of the classid = 3 & page = 1 request will be cached. No parameter, or none is used when no parameter is used. If more than one parameter is passed, different cache pages are generated on the request page even if the string parameter and value are the same but in different order. For example, default. aspx? First = 1 & last = 1 and default. aspx? Last = 1 & First = 1 although the parameters are identical, two different cache pages are generated due to different order.

Many people do not realize that when pages are output to the cache, Asp.net will also generate an HTTP header set (HTTP header) and save it to the downstream cache server, this information can be used for Microsoft Internet Security and to accelerate the server response speed. When the HTTP cache header is reset, the requested content is slowed down in network resources. When the client requests the content again, it will no longer obtain the content from the source server, the content is directly obtained from the cache.

Although page output cache does not improve the performance of your application, it can reduce the number of times cached page content is loaded from the server. Of course, this is limited to pages that can be accessed by anonymous users. Once the page is cached, authorization cannot be performed.

2) segment cache (cache a part of a page, such as a user control)

<% @ Outputcache duration = "60" varybyparam = "textbox1; textbox2" %>

In Asp.net, in addition to using cache within the page range, you can also use the output cache parameter for user control to cache user controls. Similarly, controls of the same type in a page can have multiple different caches. Different caches can be implemented based on parameters. The page cache and fragment cache can be used at the same time.

3) data cache

Data cache is a powerful and very simple caching mechanism that stores various objects for each application in the cache area. These objects can be called according to HTTP requests, however, these objects are private in different applications.
Data cache is implemented through the cache class. When an application is created, a cache class is created at the same time. The lifecycle of the cache instance is the life cycle of the application. It will be rebuilt as the application re-runs, through the cache method, we can put data objects into the cache area, and then search for and use these objects through keyword matching.
The cache class uses an excuse to control all the content to be cached, including specifying the cache time and cache method. You can add cache objects using the following methods:

Cache ["keyword"] = value of the keyword;

Then access this object using the following method:

String mkeyvalue = "";
If (Cache ["keyword"]! = NULL)
{
Mkeyvalue = cache ["keyword"];
}

Note the differences between page. cache and httpcontext. Current. cache:
They refer to the same object. In the page, page. cache. use httpcontext. current. cache. In some events, httpruntime is used because it does not have httpcontext. cache.

Data Cache expiration dependency Condition

In a sense, cache and application are the same and are all common objects. To achieve a balance between the cache and Data Validity, you can set a cache expiration Policy as needed.

File dependency
Cache. insert ("mydata", source, new cachedependency (server. mappath ("authors. xml ")));
The meaning of this Code is that when the authors. xml file does not change, the cache mydata is always valid.

Time dependency
Set the expiration time to 1 hour. This is an absolute expiration time.
Cache. insert ("mydata", source, null, datetime. Now. addhours (1), timespan. Zero );

Relatively expired dependency
The cache will expire 20 minutes after the dataset does not change.
Cache. insert ("mydata", source, null, datetime. maxvalue, timespan. fromminutes (20 ));

Example:

// Absolutely expired !!! (Used to save public data objects with a small amount of data, which can be any object)
// Set
If (system. Web. httpcontext. Current. cache ["OK"] = NULL)
System. web. httpcontext. current. cache. insert ("OK", "data", null, datetime. now. addseconds (300), system. web. caching. cache. noslidingexpiration );
// Read
If (system. Web. httpcontext. Current. cache ["OK"]! = NULL)
This. response. Write (convert. tostring (system. Web. httpcontext. Current. cache. Get ("OK ")));

Note:
You cannot use the Cache during web form debugging. Otherwise, your modifications to the page will not be explicitly loaded before the cache expires. The correct method should be to add cache commands to pages, user controls, or objects to be cached after the debugging is completed. Finally, create a deployment and installation project and generate the installation package. Then, you can release your product on the server.

For details, refer:
Http://hi.baidu.com/erics_lele/blog/item/674e46e7622f262cb83820c6.html
Http://blog.csdn.net/chengking/archive/2005/10/03/494545.aspx

2. Pre-request Cache

Although the cache API is designed to save data for a certain period of time, the pre-request cache only stores the content of a request in a certain period of time. If a request is frequently accessed and only needs to be extracted, applied, modified, or updated once. The request can be pre-cached. Here is an example.

In the CS forum application, the server control of each page requires custom data used to determine its skin (skin, to determine which style sheet to use and other personalized things. Some of the data here may need to be saved for a long time. For example, if the skin data of the control is not saved for some time, it only needs to be applied once and then can be used all the time.

To implement pre-request caching, use the httpcontext class of Asp.net. Instances of the httpcontext class are created in each request and can be accessed anywhere during the request through the httpcontext. Current attribute. The httpcontext class has an items set attribute. During the request, all objects and data are added to this set for caching. Similar to the high-frequency data access through cache, you can use httpcontext. items to cache the basic data that each request uses. The logic behind it is simple: we add a data to httpcontext. items, and then read the data from it.

5. Configure web. config

1. Disable the debugging mode.

Remember to Disable debug mode before deploying production applications or performing any performance measurements. If the debug mode is enabled, the performance of the application may be greatly affected.

<Compilation defaultlanguage = "C #" DEBUG = "false"/>

2. Adjust the number of threads for each auxiliary process of the application if necessary

The request structure of ASP. net tries to strike a balance between the number of threads executing the request and the available resources. An application that uses sufficient CPU power is known. This structure determines the number of requests that can be executed simultaneously based on the CPU power available for requests. This technology is called thread-control. However, in some conditions, the thread-control algorithm is not very effective. By using the pipeline instance count performance counter associated with the performance object of ASP. NET applications, You can monitor thread-control in perfmon.

When a page calls external resources, such as database access or XML Web Services requests, the page requests usually stop and release the CPU. If a request is waiting for processing and a thread in the thread pool is free, the waiting request will start to be processed. Unfortunately, sometimes this may lead to a large number of concurrent requests and many waiting threads on the Web server, which have adverse effects on server performance. Generally, if the gate factor is the response time of external resources, too many requests are waiting for resources, which is not helpful for the Web server throughput.

To alleviate this problem, you can manually set the number of threads in the process by changing the maxworkerthreads and maxiothreads attributes of the <processmodel> node in the machine. config configuration file.

Note that the auxiliary thread is used to process ASP. NET requests, while the IO thread is used to provide services for data from files, databases, or XML Web Services.
The value assigned to these attributes is the maximum number of threads in each CPU type in the process. For dual-processor computers, the maximum number is twice the set value. For a four-processor computer, the maximum value is four times the set value. In any case, it is best to change the default value for computers with four or eight CPUs. The default value can be used for computers with one or two processors. However, for computers with more processors, one hundred or two hundred threads in a process may cause more disadvantages.

Note that too many threads in the process will often reduce the server speed, because the operating system will spend the CPU cycle on the maintenance thread rather than processing the request due to extra context switching.

& Lt; httpruntime maxrequestlength = "4096"
Usefullyqualifiedredirecturl = "true" minfreethreads = "8" minlocalrequestfreethreads = "4"
Apprequestqueuelimit = "300"
Executiontimeout = "45"/>

Recommended Configuration Setting Default Value
-----------------------------------
Maxconnection 2 12 * # CPUs
Maxiothreads 20 100
Maxworkerthreads 20 100
Minworkerthreads 50
Minfreethreads 8 88 * # CPUs
Minlocalrequestfreethreads 4 76 * # CPUs
Apprequestqueuelimit 1000

3. Carefully select the session Status provider

ASP. NET provides three different methods for storing application session data: in-process session Status, out-of-process session status as a Windows service, and out-of-process session Status in the SQL Server database. Each method has its own advantages, but the in-process session status is the fastest solution so far. If you only store a small amount of data that is prone to loss in the session state, we recommend that you use in-process providers. Out-of-process solutions are mainly used to scale applications across multiple processors or computers, or to prevent data loss during server or process restart.

<Sessionstate
Mode = "inproc"
Stateconnectionstring = "TCPIP = 127.0.0.1: 42424"
Sqlconnectionstring = "Data Source = 127.0.0.1; trusted_connection = yes"
Cookieless = "false"
Timeout = "20"
/>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.