. NET Application Performance optimization

Source: Internet
Author: User

1. ASP. NET Process Configuration optimization

The ASP. NET process model makes some process-level settings, such as how many threads are used by ASP, the time-out, how many requests are waiting for input and output, and so on. There are a number of restrictions by default. Now that the hardware is getting cheaper, the server of G-class memory is ubiquitous, so the optimization of the process configuration can get more system resources and extensions.

The Mashine.config configuration for ASP. NET 1.1 is like this

<!--

ProcessModel Attributes:

Enable= "[True|false]"-Enable ProcessModel

Timeout= "[Infinite | HH:MM:SS]-Total life of process, once expired process was shutdown and a new process is created

Idletimeout= "[Infinite | HH:MM:SS] "-Total idle life of the process, once expired process is automatically shutdown

Shutdowntimeout= "[Infinite | HH:MM:SS] "-time process is given to shutdown gracefully before being killed

Requestlimit= "[Infinite | number]"-Total number of requests to serve before process is shutdown

Requestqueuelimit= "[Infinite | number]"-Number of queued requests allowed before process is shutdown

Restartqueuelimit= "[Infinite | number]"-Number of requests kept in queue and process is restarting

Memorylimit= "[number]"-represents percentage of physical memory process is allowed to use before process is recycled

Webgarden= "[True|false]"-Determines whether a process should be affinitized with a particular CPU

Cpumask= "[Bit mask]"-Controls number of available CPUs available for ASP. Processes (Webgarden must BES set to TRUE)

Username= "[user]"-Windows user to run the process as.

Special users: "SYSTEM": Run as LocalSystem (High privilege admin) account.

"Machine": the Run as low privilege the user account named "ASPNET".

Other users:if domain was not specified, and current machine name was assumed to being the domain name.

Password= "[AutoGenerate | password]"-Password of Windows user. For special users (SYSTEM and machine), specify "AutoGenerate".

Loglevel= "[all| none| Errors] "-Event types logged to the event log

Clientconnectedcheck= "[HH:MM:SS]"-time a request is left in the queue before ASP. Does a client connected check

Comauthenticationlevel= "[default| none| Connect| call| Pkt| pktintegrity| PktPrivacy] "-level of authentication for DCOM security

Comimpersonationlevel= "[default| anonymous| identify| impersonate| Delegate] "-Authentication level for COM security

Responsedeadlockinterval= "[Infinite | HH:MM:SS] "-For deadlock detection, timeout for responses when there is executing requests.

Maxworkerthreads= "[number]"-Maximum number of worker threads per CPU in the thread pool

Maxiothreads= "[number]"-Maximum number of IO threads per CPU in the thread pool

servererrormessagefile= "[filename]"-Customization for "Server unavailable" message

When ASP. Running under IIS 6 in native mode, the IIS 6 process model is

Used and settings in this section is ignored. Please use the IIS administrative

UI to configure things like process identity and cycling for the IIS

Worker process for the desired application

-

<processmodel

Enable= "true"

timeout= "06:20:00"

idletimeout= "Infinite"

shutdowntimeout= "0:00:05"

requestlimit= "Infinite"

requestqueuelimit= "5000"

restartqueuelimit= "10"

memorylimit= "60"

Webgarden= "false"

cpumask= "0xFFFFFFFF"

Username= "Machine"

Password= "AutoGenerate"

Loglevel= "Errors"

clientconnectedcheck= "0:00:05"

Comauthenticationlevel= "Connect"

Comimpersonationlevel= "Impersonate"

Responsedeadlockinterval= "00:03:00"

Maxworkerthreads= "150"

maxiothreads= "80"

/>

The configuration of the mashine.config for ASP. NET 2.0 is this:

<system.web>

<processmodel autoconfig= "true"/>

</system.web>

You should change the configuration to customize the way that ASP. NET threads work by setting different properties with some values. As shown below:

<processmodel

Enable= "true"

timeout= "Infinite"

idletimeout= "Infinite"

shutdowntimeout= "00:00:05"

requestlimit= "Infinite"

requestqueuelimit= "5000"

restartqueuelimit= "10"

memorylimit= "60"

Webgarden= "false"

cpumask= "0xFFFFFFFF"

Username= "Machine"

Password= "AutoGenerate"

Loglevel= "Errors"

clientconnectedcheck= "00:00:05"

Comauthenticationlevel= "Connect"

Comimpersonationlevel= "Impersonate"

Responsedeadlockinterval= "00:03:00"

Responserestartdeadlockinterval= "00:03:00"

Autoconfig= "false"

maxworkerthreads= "100"

maxiothreads= "100"

Minworkerthreads= "40"

miniothreads= "30"

Servererrormessagefile= ""

Pingfrequency= "Infinite"

pingtimeout= "Infinite"

Asyncoption= "20"

Maxappdomains= "2000"

/>

There are some default values in addition to the following values:

maxWorkerThreads: The default per process is 20 threads. On a dual-core server, the system allocates 40 threads to ASP. NET, which means that ASP. NET can handle 40 concurrent requests concurrently on a dual-core server. In order to add threads to every process of ASP, I have set 100. You can set this property if your application has a strong CPU and requires more requests. In particular, your network uses a large number of WebService or uploads/downloads large amounts of data that do not transfer the pressure to the CPU. When ASP. NET ran out of all the threads, it stopped receiving more responses. Requests are queued until the threads in the other work are freed. This situation often occurs when the site receives more than expected clicks, in which case if you have a spare CPU, increase the number of threads in the process.

Maxiothreads: The default is 20. In a dual-core server, the system provides 40 I/O threads to ASP.NET.I/O requests for file reads and writes, database reads, WebService calls, HTTP requests, and so on. You can set it up a bit higher, especially when your site does concurrent uploads/downloads and WebService calls.

minWorkerThreads: When the ASP. NET free worker thread is below this value, ASP. NET will push some requests into the queue. So you can set a low value to increase the current number of requests. Of course, this value can not be set too low, because the site to do some background processing and parallel processing, these tasks are required to run some threads.

Miniothreads: Equivalent to minWorkerThreads, just a setup for I/O processes. It can be set lower than in case because there is nothing wrong with the I/O parallel threading thread.

MemoryLimit: Specifies the maximum memory usage size. It specifies a percentage of all system memory, which is the maximum amount of memory that can be used to specify the system processing process. If there is only your own website on the server and there is no other process that uses memory, you can set it up a bit higher, for example: 80. If your site has a memory leak problem, you'd better set this value lower, so that the leaked memory will be released soon, so that the site will keep the normal operation. Especially when you're using COM components to cause memory leaks. Of course, this is just a temporary solution, and eventually you have to solve the problem of memory leaks.

In addition to processmodel, ASP can set the maximum number of requests for a single IP:

<system.net>

<connectionManagement>

<add address= "*" maxconnection= "/>"

</connectionManagement>

</system.net>

Default is 2, this value is too low. This means that each IP can have up to two requests to your site, which can cause requests to jam. This is set to 100, and of course you can set it higher if necessary.

http://support.microsoft.com/kb/821268

Calculation Formula (Maxworkerthreads*number of CPUs)-minfreethreads

Http://blogs.msdn.com/wenlong/archive/2008/04/21/wcf-request-throttling-and-server-scalability.aspx

2. Optimal Pipeline optimization

Some ASP. NET default HttpModules manages the requested pipeline and each request. For example: SessionStateModule intercepts every request and analyzes session cookies To load the appropriate session in the HttpContext. But not all modules are required, such as: if you do not membership, you do not need to configure the FormsAuthentication module, if you do not use Windows authentication, you do not have to configure wind Owsauthentication, these modules are only contained within the pipeline, and execute some code that is not required for each request. Default module definition in Machine.config ($WINDOWS $microsoft.netframework$version$config)

As shown below:

<add name= "OutputCache" type= "System.Web.Caching.OutputCacheModule"/>

<add name= "Session" type= "System.Web.SessionState.SessionStateModule"/>

<add name= "WindowsAuthentication"

Type= "System.Web.Security.WindowsAuthenticationModule"/>

<add name= "FormsAuthentication"

Type= "System.Web.Security.FormsAuthenticationModule"/>

<add name= "Passportauthentication"

Type= "System.Web.Security.PassportAuthenticationModule"/>

<add name= "urlauthorization" type= "System.Web.Security.UrlAuthorizationModule"/>

<add name= "fileauthorization" type= "System.Web.Security.FileAuthorizationModule"/>

<add name= "Errorhandlermodule" type= "System.Web.Mobile.ErrorHandlerModule,

System.Web.Mobile, version=1.0.5000.0,

Culture=neutral, publickeytoken=b03f5f7f11d50a3a "/>

If you want to remove these default settings, simply add the <remove> node to your Web. config.

<!--remove unnecessary nodes and increase request speed--

<remove name= "WindowsAuthentication"/>

<remove name= "Passportauthentication"/>

<remove name= "URLAuthorization"/>

<remove name= "Fileauthorization"/>

The above configuration applies to database-based form authentication sites. So these nodes can be deleted.

3. WCF performance tuning parameters for WCF services that are not hosted by IIS

<runtime>

<gcserverenabled= "true"/>

</runtime>

When it comes to a large number of requests, consider using the Servicethrottlingbehavior property of WCF.

Current limit allows developers to limit the number of client connections and the load on the service. Current throttling avoids maximizing service and maximizing allocation and use of critical resources. Once the throttling technology is introduced, once the configured settings are exceeded, WCF automatically places the callers waiting to be processed in the queue and then takes them out of the queue in turn. When waiting for processing calls in the queue, the client obtains a TimeoutException exception if the client's call times out. Each service type can apply current-limiting technology, which means that it affects all instances of the service and all endpoints of the service type. This is achieved by limiting the flow to correlate with each channel dispatcher used by the service. ”

The current limit is defined by the Servicethrottlingbehavior class and includes three important attributes: Maxconcurrentcalls, MaxConcurrentSessions, Maxconcurrentinstances, The default values are 16, 10, and Int.maxvalue, respectively.

Name

Description

Maxconcurrentcalls

Gets or sets a value that specifies the maximum number of messages being processed in the entire ServiceHost.

Maxconcurrentinstances

Gets or sets a value that specifies the maximum number of InstanceContext objects that can be executed at a time in the service.

MaxConcurrentSessions

Gets or sets a value that specifies the maximum number of sessions that the ServiceHost object can accept at a time.

Here we set the current throttling behavior of the service. Specific as follows:

<serviceBehaviors>

<behavior name= "Wcfservice.wcfservicebehavior" >

<servicetimeouts transactiontimeout= "00:01:00"/>

<servicemetadata httpgetenabled= "true"/>

<servicedebug includeexceptiondetailinfaults= "false"/>

<servicethrottling maxconcurrentcalls= "maxconcurrentinstances=", "maxconcurrentsessions="/>-- >

</behavior>

</serviceBehaviors>

http://blogs.msdn.com/wenlong/archive/2009/09/06/ Crack-throttling-debugging-wcf-timeoutexception-for-a-middle-tier-application.aspx

Operating system parameter tuning

1, TCP/IP parameter adjustment

Option TcpTimedWaitDelay:

Determines the time that TCP/IP must pass before it can release a closed connection and reuse its resources. This interval between closing and releasing is known as the time_wait state or twice times the maximum segment life cycle (2MSL) state. During this time, reopening the connection to the client and the server costs less than establishing a new connection. Reducing this value allows TCP/IP to release closed connections more quickly, providing more resources for new connections. Adjust this parameter if you are running an application that needs to quickly release and create new connections, and because there are many connections in time_wait that cause low throughput. Windows default 4 minutes, adjusted to 60 seconds

Option MaxUserPort

Determines the highest port number that TCP/IP can specify when an application requests an available user port from the system. The default value is 1024-5000. Adjusted to 12000

2, database connection pool parameter adjustment

Connection pooling reduces the number of times a new connection needs to be opened. The pool process retains ownership of the physical connection. Manage connections by reserving a set of active connections for each given connection configuration. As long as the user calls Open on the connection, the pool process checks to see if a connection is available in the pool. If a pool connection is available, the connection is returned to the caller instead of opening a new connection. When an application calls close on the connection, the pool process returns the connection to the active connection pool set instead of actually closing the connection. Once the connection is returned to the pool, it can be reused in the next Open call.

Pool connections can be established only if the same connection is configured. ADO maintains multiple pools at the same time, one pool per configuration. The connection is divided into multiple pools by the connection string and the Windows identity (when using integrated security). The pool connection is also established based on whether the connection has been enlisted in the transaction.

Pooled connections can significantly improve the performance and scalability of your application. By default, connection pooling is enabled in ADO. Unless explicitly disabled, the connection is optimized by the pool process when it is opened and closed in the application. You can also provide several connection string modifiers to control the behavior of the connection pool.

When the connection is first opened, a connection pool is created based on the exact matching algorithm that associates the pool with the connection string in the connection. Each connection pool is associated with a different connection string. When you open a new connection, a new pool is created if the connection string does not exactly match the existing pool. Pool connections are created by process, by application domain, by connection string, and by Windows identity (when using integrated security). The connection string must also be exactly matched, and the keywords provided for the same connection in different order will be grouped into separate pools.

If minpoolsize is not specified or specified as zero in the connection string, the connection in the pool is closed after a period of inactivity. However, if the specified minpoolsize is greater than 0, the connection pool is not destroyed until the AppDomain is unloaded and the process ends. The maintenance of an inactive or empty pool requires minimal system overhead.

Connection pooling is created for each unique connection string. When a pool is created, multiple connection objects are created and added to the pool to meet the minimum pool size requirements. The connection is added to the pool as needed, but cannot exceed the specified maximum pool size (the default value is 100). The connection is released back into the pool when it is closed or disconnected.

When a SqlConnection object is requested, the object is fetched from the pool if there is an available connection. The connection is to be available, must not be used, has a matching transaction context or is not associated with any transaction context, and has a valid link to the server.

The connection pooling process satisfies these connection requests by reallocating the connection when the connection is released back into the pool. If the maximum pool size has been reached and no available connections exist, the request will be queued. The pool process then attempts to reestablish any connections until the timeout is reached (the default value is 15 seconds). If the pool process cannot satisfy the request before the connection times out, an exception is thrown.

You receive a 2269 event message when you try to start a worker process in IIS 6.0

http://support.microsoft.com/?kbid=896286

The server could not allocate memory in the system paged pool

http://support.microsoft.com/kb/312362

Errors logged in the HTTP API

Http://support.microsoft.com/kb/820729/zh-cn

http://blogs.msdn.com/david.wang/archive/2005/09/21/ Howto-diagnose-iis6-failing-to-accept-connections-due-to-connections-refused.aspx

. NET Application Performance optimization

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.