[英]Should I create a brand new SqlConnection each time I want to use it, or just attempt to re-open an existing connection each time?
I have a long-running .NET process (a Windows service), which talks to a SQL Server. 我有一个长期运行的.NET进程(Windows服务),它与SQL Server通讯。
Originally, I opened a connection when the service started up, and just kept it open. 最初,我在服务启动时打开了一个连接,并保持打开状态。 However, occasionally a network hiccup or reboot of the SQL Server would break that connection, and my process wouldn't know this.
但是,偶尔出现网络故障或SQL Server重新启动会中断该连接,而我的进程也不知道这一点。 It would attempt to keep throwing SQL against a closed connection.
它将尝试对关闭的连接不断抛出SQL。
Trying to maintain an open connection like that was clearly me trying to be too clever. 试图保持像这样的开放连接显然是我试图变得太聪明。 So, do I:
我也是:
SqlConnection
object every time SqlConnection
对象 For the latter (#2), I have this code: 对于后者(#2),我有以下代码:
if(connection.State != ConnectionState.Open)
{
connection.Open();
}
I only have to do this because the connection already exists. 我只需要这样做,因为连接已经存在。 If I created the connection fresh each time (#1), clearly it would be closed and I would need to open it.
如果我每次都重新创建连接(#1),那么显然它将关闭并且需要打开它。
What I'm hoping to do is take advantage of SQL connection pooling to actually not open a new connection every time, but just let the connection pool manage that -- give me an open connection when it has one, or open a new one when it doesn't. 我希望做的是利用SQL连接池来实际上不是每次都打开一个新连接,而只是让连接池来管理它-当有一个连接时给我一个打开的连接,或者在有一个连接时给我一个打开的连接。没有。
To achieve this, does it matter if I create the connection fresh each time (#1), or if I just-reuse a connection and attempt to re-open it each time (#2)? 为此,是否每次都重新创建连接(#1)还是重新使用连接并每次尝试重新打开连接(#2)都重要吗?
Connection pooling means that even if you do (1), under the hood, the framework will do (2) for you for improved performance. 连接池意味着即使在后台执行(1),框架也将为您执行(2),以提高性能。 So you can feel free to create a new connection each time.
因此,您可以随时创建一个新的连接。
It's worth pointing out that, for the most part, the pooling only applies to identical connection strings. 值得指出的是,在大多数情况下,池化仅适用于相同的连接字符串。 So if you change certain options, those connections may not be pooled.
因此,如果更改某些选项,则可能不会合并这些连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.