ADO.NET之串連池技術的使用詳解

來源:互聯網
上載者:User

串連到資料庫伺服器通常需要一定的時間,且伺服器也需要一定的資源來處理串連。Web應用程式有時處理成千上萬的串連,需要相當多的資源來處理串連。ADO.NET具有串連池的特性,串連池的功能是保留一定數量的串連,當使用者使用相同的連接字串再次串連伺服器時,ASO.NET將使用串連池中的串連而不用重新發起一次串連過程。當調用Close方法關閉串連時,ADO.NET將使用串連池中的串連而不用重新發起一次串連過程。當調用Close方法關閉串連時,串連將會返回到串連池中,下次再次調用Open方法時,將從串連池中取出一個串連使用。

資料庫連接字串預設為啟用串連池。使用串連池可以在連接字串中用pooling=true/false來控制,設定串連池最大值和最小值可以使用Max Pool Size=200;Min Pool Size=1; 進行控制。

下邊建立一個控制台應用程式來示範串連池的使用,其實我們僅僅是在Connection String中使用pooling=false/true來控制,預設是使用串連池技術的,也就是pooling=true:

複製代碼 代碼如下:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Threading;

namespace ConsoleApplication1
{
class Program
{
private static readonly string connectionString1 = @"Data Source=.;Initial Catalog=Northwind;Integrated Security=True;pooling=true;";//預設值即為true,所以可省略pooling=true
private static readonly string connectionString2 = @"Data Source=.;Initial Catalog=Northwind;Integrated Security=True;pooling=false;";
static void Main(string[] args)
{
long startTicks1 = DateTime.Now.Ticks;
using (SqlConnection conn1 = new SqlConnection(connectionString1))
{
for (int i = 0; i < 100; i++)
{
conn1.Open();
conn1.Close();
}
}
long endTicks1 = DateTime.Now.Ticks;
long usedTicks1 = endTicks1 - startTicks1;
Console.WriteLine("Used time: " + usedTicks1);

long startTicks2 = DateTime.Now.Ticks;
using (SqlConnection conn2 = new SqlConnection(connectionString2))
{
for (int i = 0; i < 100; i++)
{
conn2.Open();
conn2.Close();
}
}
long endTicks2 = DateTime.Now.Ticks;
long usedTicks2 = endTicks2 - startTicks2;
Console.WriteLine("Used time: " + usedTicks2);

}

}

}

輸出結果:複製代碼 代碼如下:pooling=true: 710040
pooling=false: 3100177

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.