很多人認為 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.
以上摘自 http://msdn.microsoft.com/en-us/library/8xx3tyca%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
新聞熱點
疑難解答