很多人认为 SqlConnection 的连接是不耗时的,理由是循环执行 SqlConnection.Open 得到的平均时间几乎为0,但每次首次open 时,耗时又往往达到几个毫秒到几秒不等,这又是为什么呢?
首先我们看一下 MSDN 上的权威文档上是怎么说的
Connecting to a database server typically consists of several time-consuming steps. A physical channel such as a socket or a named pipe must be established, the initial handshake with the server must occur, the connection string information must be parsed, the connection must be authenticated by the server, checks must be run for enlisting in the current transaction, and so on.
以上摘自 %28VS.80%29.aspx
也就是说物理连接建立时,需要做和服务器握手,解析连接字符串,授权,约束的检查等等操作,而物理连接建立后,这些操作就不会去做了。这些操作是需要一定的时间的。所以很多人喜欢用一个静态对象存储 SqlConnection 来始终保持物理连接,但采用静态对象时,多线程访问会带来一些问题,实际上,我们完全不需要这么做,因为 SqlConnection 默认打开了连接池功能,当程序 执行 SqlConnection.Close 后,物理连接并不会被立即释放,所以这才出现当循环执行 Open操作时,执行时间几乎为0.
下面我们先看一下不打开连接池时,循环执行 SqlConnection.Open 的耗时
复制代码 代码如下:
public static void OpenWithoutPooling()
{
string connectionString = "Data Source=192.168.10.2; Initial Catalog=News;Integrated Security=True;Pooling=False;";
Stopwatch sw = new Stopwatch();
sw.Start();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
}
sw.Stop();
Console.WriteLine("Without Pooling, first connection elapsed {0} ms", sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
for (int i = 0; i < 100; i++)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
}
}
sw.Stop();
Console.WriteLine("Without Pooling, average connection elapsed {0} ms", sw.ElapsedMilliseconds / 100);
}
SqlConnection 默认是打开连接池的,如果要强制关闭,我们需要在连接字符串中加入 Pooling=False
调用程序如下:
复制代码 代码如下:
Test.SqlConnectionTest.OpenWithoutPooling();
Console.WriteLine("Waiting for 10s");
System.Threading.Thread.Sleep(10 * 1000);
Test.SqlConnectionTest.OpenWithoutPooling();
Console.WriteLine("Waiting for 600s");
System.Threading.Thread.Sleep(600 * 1000);
Test.SqlConnectionTest.OpenWithoutPooling();
下面是测试结果
Without Pooling, first connection elapsed 13 ms
Without Pooling, average connection elapsed 5 ms
Wating for 10s
Without Pooling, first connection elapsed 6 ms
Without Pooling, average connection elapsed 4 ms
Wating for 600s
Without Pooling, first connection elapsed 7 ms
Without Pooling, average connection elapsed 4 ms
从这个测试结果看,关闭连接池后,平均每次连接大概要耗时4个毫秒左右,这个就是建立物理连接的平均耗时。
下面再看默认情况下的测试代码
复制代码 代码如下:
public static void OpenWithPooling()
{
string connectionString = "Data Source=192.168.10.2; Initial Catalog=News; Integrated Security=True;";
Stopwatch sw = new Stopwatch();
sw.Start();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
}
sw.Stop();
Console.WriteLine("With Pooling, first connection elapsed {0} ms", sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
for (int i = 0; i < 100; i++)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
}
}
sw.Stop();
Console.WriteLine("With Pooling, average connection elapsed {0} ms", sw.ElapsedMilliseconds / 100);
}
调用代码
复制代码 代码如下: