using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
public class ConnStr
{
public string Flag { get; set; }
public string ConnString { get; set; }
}
class Program
{
static void Main(string[] args)
{
string connStringNoPooling = @"data source=(local)\sqlserver2014;initial catalog=master;Integrated Security=True;pooling=false;";
string connStringDefault = @"data source=(local)\sqlserver2014;initial catalog=master;Integrated Security=True;";
string connStringPooling100 = @"data source=(local)\sqlserver2014;initial catalog=master;Integrated Security=True;pooling=true;connection lifetime=10;min pool size = 100;max pool size=100; ";
string connStringPooling200 = @"data source=(local)\sqlserver2014;initial catalog=master;Integrated Security=True;pooling=true;connection lifetime=10;min pool size = 100;max pool size=200; ";
string connStringPooling300 = @"data source=(local)\sqlserver2014;initial catalog=master;Integrated Security=True;pooling=true;connection lifetime=10;min pool size = 100;max pool size=300; ";
string connStringPooling500 = @"data source=(local)\sqlserver2014;initial catalog=master;Integrated Security=True;pooling=true;connection lifetime=10;min pool size = 100;max pool size=500; ";
string connStringPooling1000 = @"data source=(local)\sqlserver2014;initial catalog=master;Integrated Security=True;pooling=true;connection lifetime=10;min pool size = 100;max pool size=1000; ";
List<ConnStr> list = new List<ConnStr>() {
new ConnStr(){ Flag="无连接池",ConnString=connStringNoPooling }
,new ConnStr(){ Flag="默认 ",ConnString=connStringDefault }
,new ConnStr(){ Flag="最大100 ",ConnString=connStringPooling100 }
,new ConnStr(){ Flag="最大200 ",ConnString=connStringPooling200 }
,new ConnStr(){ Flag="最大300 ",ConnString=connStringPooling300 }
,new ConnStr(){ Flag="最大500 ",ConnString=connStringPooling500 }
,new ConnStr(){ Flag="最大1000",ConnString=connStringPooling1000 }
};
foreach (ConnStr connObj in list)
{
Stopwatch sw = Stopwatch.StartNew();
Parallel.For(0, 1000, item =>
{
TestQuery(connObj.ConnString);
});
sw.Stop();
Console.WriteLine("{0} => 消耗毫秒数:{1}", connObj.Flag, sw.ElapsedMilliseconds);
}
Console.Read();
}
private static void TestQuery(string connString)
{
string sql = "select top 1 * from dbo.spt_values;WAITFOR DELAY '00:00:00.500'";
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
}
}
}
如此看来, 连接数增加对增加并发有一定的改善作用,但达到一定程度后不再上升。可能 256 ~ 512 比较合适。
可能跟CPU性能也有关系, 哪位有比较强悍的机器可以一试。