The pool in net

Source: Internet
Author: User
Tags connection pooling

Net of various pools in. NET, there are four commonly used pools: string detention pool, thread pool, application pool, database connection pool. String Detention Pool

Strings in. NET are immutable objects, and modifying the value of a string variable results in a new object. To reduce performance consumption and reduce the size of the assembly. NET provides the function of string interning, literal translation is the character of strings detained. The so-called string detention pond (intern pool) is actually a hash table, the key is the string literal, and the value is a reference to the string object on the managed heap. However, if the table is too large, it can adversely affect performance. When an assembly is loaded, different versions of the CLR are not the same for whether to retain the string literal in the assembly metadata, as determined by the compile-time value. But explicitly calls string. The Intern method puts the string literal into the pool.

When we assign a literal value to a string type variable, the CLR first looks at the string pool for the exact same string (case-sensitive), returns the corresponding reference if any, and, if none, creates a new object and adds it to the string pool to return the reference. However, if you assign a value to a string variable at run time (for example, using the New keyword), the string pool is not used.

C # provides two methods related to string pooling:

If STR does not create a new string object in the string pool and returns the reference
Public STATICC string Intern (String str);
If STR does not create a new string object in the string pool and returns null
Public STATICC string isinterned (String str);
The sample code is as follows:

Copy Code
var str = "ABC";
var Str01 = "abc";
Running constant quantity
var str02 = new String (new char[] {' A ', ' B ', ' C '});
Compile-time constant (the compiled code can be viewed by the anti-compiler)
String str03 = "a" + "BC";

Console.WriteLine ($ "Str01==str is {referenceequals (Str01, str)}");
Console.WriteLine ($ "Str02==str is {referenceequals (Str02, str)}");
Console.WriteLine ($ "Str03==str is {referenceequals (str03, str)}");

var str04 = string.isinterned (new String (new char[] {' A ', ' B '});
Console.WriteLine ($ "STR04 = = NULL is {str04 = = null}");
var str05 = string.isinterned ("Abdgj");
Console.WriteLine ($ "str05={str05}");

var str06 = String.intern (new String (new char[] {' A ', ' B ', ' d ', ' e '});
Console.WriteLine ($ "str06={str06}");
Copy Code
The following results are obtained:

Thread pool

There is only one thread pool (MSDN) in a process. Another argument is that a thread pool in the CLR ("CLR via C #"), I agree with this argument. A process can load several different versions of the CLR, but the same version of the CLR can only have one. In summary, threads do not belong to the application domain (AppDomain).

If a thread in the thread pool has an unhandled exception, it causes the current process to be terminated with three exceptions:

ThreadAbortException, the exception is thrown when the Abort method is called to terminate the thread

AppDomainUnloadedException, this exception is thrown when the AppDomain is unloaded

When a CLR or a host process terminates a thread

In the. NET1.0 and 1.1 versions, the CLR handles unhandled exceptions in the thread pool. But doing so destroys the state in the application and even causes the program to hang, which is not conducive to debugging.

In. NET, many scenarios can use a thread pool. For example, asynchronous I/O, callbacks, registering a wait operation, using a delegate's asynchronous method invocation, and a socket connection in System.Net.

However, you should avoid using threads in the thread pool in the following scenarios:

When you need to use a foreground thread
When a thread needs a specific priority
When you need to perform more time-consuming operations. Because the number of threads in the thread pool is capped, prolonged blocking can affect the handling of other tasks
When a thread needs to be placed on a single apartment (single-threaded apartment). Threads in a thread pool are in a multithreaded apartment (multithreaded apartment)
Need to give thread a stable identity or thread for a specific task
There are two types of threads in a thread pool: worker threads (worker) and I/O threads (I/O completion Port). These two threads are only useful and are not fundamentally different.

The minimum number of threads in the thread pool defaults to the number of logical cores for the processor. That is, on a 4-core computer, the default minimum number of worker threads and I/O threads in the thread pool is 4. Theoretically, the maximum number of threads in a thread pool is limited only by the available memory size, but the thread pools limit the number of threads available within the process.

Threadpool.getminthreads (out Var minworkerthreadcount, out Var miniothreadcount);
Console.WriteLine ($ "Minworkerthreadcount={minworkerthreadcount},miniothreadcount={miniothreadcount}");
Threadpool.getmaxthreads (out Var maxworkerthreadcount, out Var maxiothreadcount);
Console.WriteLine ($ "Maxworkerthreadcount={maxworkerthreadcount},maxiothreadcount={maxiothreadcount}");
The results of the operation are as follows:

When an app uses a thread in the thread pool to work, if there are no threads in the thread pool, a new thread is created to meet the needs, and when the number of threads in the thread pool reaches the minimum number of threads set and no idle threads, it waits for a period of time (up to 500ms). After 500ms, there is still no idle thread available for use and a new thread is created to work, but the number of threads in the thread pool does not exceed the maximum number of threads set.

When a thread in a thread pool is idle for a period of time (different CLR, this time is different), it is destroyed.

When the application load is low, the number of threads in the thread pool may also be less than the minimum number of threads set.

The machine.config thread pool is configured as follows (. NET configuration file system see: ASP. Hierarchy and Inheritance):




To configure the thread pool size:

This configuration is independent of how many CPU logical cores are handled
Threadpool.setmaxthreads (1000, 800);
Threadpool.setminthreads (20, 20);
Asp. NET can also be configured through a configuration file, which is configured for each CPU logical core:






Doing so will cause an error when the app starts: using a section registered as allowdefinition= ' machineonly ' outside of the Machine.config file is wrong. The Machine.config file needs to be modified.

Proper configuration of the thread pool can be helpful for application performance improvement.

Application Pools

In IIS5, a server has only one worker process, and different applications use the AppDomain to differentiate, and when a worker process fails, all apps are affected. The concept of application pooling has been introduced from IIS6, where application pools isolate different applications from one another to prevent interaction between different applications. When you deploy an ASP. NET application, the application pool typically has two managed pipeline modes to choose from: Integrated mode and Classic mode.

By default, one application pool has a worker process that can set up multiple worker processes depending on the situation, but takes into account resource consumption and local cache synchronization issues.

Worker process isolation in IIS6 and IIS5 is at the server level. Different worker process isolation modes cannot be used on the same server. Starting with IIS7, the worker process isolation mode is based on the application pool, so that different isolation modes can be used on the same server.

In the application pool-advanced settings, you can set up the application pool, such as queue length, worker process recycling mechanism, and so on.

Database Connection Pool

The process of establishing a connection with the database server is time-consuming, for this, ADO. NET uses a connection pool for optimization. Different data provider in. NET handle connection pooling differently. By default, the connection pool optimization is enabled by ADO, and you can configure whether connection pooling is enabled through the connection string.

Connection pooling reduces the number of connections to the database and maintains a set of active database connections in the connection pool. When we call IDbConnection's Open method, the CLR goes to the connection pool to find out if there are any available connections, and if so, returns the connection without having to establish a new connection to the database. When we call the Close method of IDbConnection, the connection is reclaimed by the connection pool but is continuously connected to the database for the next use. The connection is destroyed when the connection in the connection pool is idle for a period of time (about 4-8 minutes) or if the connection pool detects that the connection has been disconnected from the server (requiring communication with the server to detect that the connection is broken).

The first time you open a connection, ADO. NET establishes a connection pool based on the connection configuration. Ado. NET creates a connection pool for each connection configuration, so if you have multiple different connection configurations (for example, different connection strings) in your program, you will have multiple connection pools.

If there is a timeout or other login error in the connection pool, an exception is thrown, and the connection will fail in the next 5s, and the 5s clock becomes a blocking period. If the connection fails after the end of the blocking period, a new blocking period is entered, and the new blocking period is twice times longer than the last blocking period, but up to 1 minutes.

If the value of Minpoolsize is not set in the connection string, or if the value is set to 0, the connection pool is destroyed when there is no active connection in the pool. However, if the value of minpoolsize is set to greater than 0, the connection pool is destroyed only when the AppDomain is unloaded. When a more serious error occurs in the connection pool, the connection pool cleans itself.

The maximum number of connections in the connection pool defaults to 100, and when the number of connections in the connection pool reaches the upper limit and is occupied, the new request goes into the queue until the wait time exceeds 15s (the default) throws an exception.

A database connection is recommended using the following notation so that when the using statement ends, the connection object is returned to the connection pool for the next request to be used.

using (IDbConnection conn = new SqlConnection ())
{

}
Conclusion
Above, is my study of a bit of experience, the wrong place to look at you a lot of advice.

Recommended Reading
Thread Pool
Exceptions in Managed Threads.
Stackexchange.redis Timeout
The performance optimization of 5.28 large-pressure measurement-thread pool related problems (improper thread pool configuration)
Worker threads (worker thread) and I/O threads

Introduction to IIS architectures
ASP. Integration with IIS 7
ASP. NET Configuration File Hierarchy and inheritance
The thread pool in IIS and ASP.
IIS maximum number of connections and queue lengths
IIS application pool crashes due to System.Threading.Tasks.Task
HTTP. SYS detailed
How IIS Performs
IIS ASP. The analysis of the process pattern of net

SQL Server Connection Pooling (ADO)
Connection Pooling

Copyright notice

The pool in net

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.