The link to the article is as follows:
http://www.cnblogs.com/LoveJenny/archive/2011/10/31/2229738.html
1: Is SqlConnection thread-safe?
It can be known that using a Connection to execute a Sql statement in a multithreaded environment isNot safeTarget.
SqlConnection is not thread safe, so multithreading is bound to be a problem. In fact, .net automatically provides connection pool management, as long as the connection string is the same (must be exactly the same), it will be in the same pool, open and close are actually taking a connection from the pool and putting the connection back into the pool, which will not cause performance problems. Therefore, after each connection is opened, it should be closed as soon as possible after use, so that the connection can be returned to the pool for other programs to use.
2: Why do people still use the above writing method to create Connections?
I think they might think that creating multiple Connections is time-consuming, and that multiple Connections take up memory, affect performance, etc.
3: Does every new SqlConnection take up memory and resources, affecting performance?
This is blind thinking, blind worrying.
Because"Creating multiple connections" does not necessarily create multiple new database connectionsDatabase connection is a valuable resource, as far as MS SQL Server is concerned, this valuable resource will be optimized internally, and the connection will be reused.
The connection pool is provided by .net, there is a Pooling property in the connection string, the default is true, that is, the connection pool is turned on by default, this has nothing to do with sql server, if you write Pooling=false in the connection string, then there is no connection pool, this is completely . .NET optimization.
Exploring the Consequences of Using the Same Database Connection in Multiple Threads Article link: http://www.th7.cn/Program/java/201503/415005.shtml
Summary: In a multi-threaded environment, using a single connection can cause transaction confusion without thread-safe handling of the connection.... Affects the use of JDBC transactions...
|