配置文件:sql
<?xml version="1.0"?> <configuration> <startup> <supportedRuntime version="v2.0.50727"/> </startup> <appSettings> <add key="Test" value="Data Source=10.68.108.3;Initial Catalog=ZhanJiang;Persist Security Info=True;User ID=eerpsa;Password=eerpP@ssword;Asynchronous Processing=true;MultipleActiveResultSets=true"/> </appSettings> </configuration>
異步操做的鏈接字符串要加入:Asynchronous Processing=true;MultipleActiveResultSets=trueapp
測試代碼:異步
using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Diagnostics; using System.Linq; using System.Text; namespace TestConsoleApp { [NUnit.Framework.TestFixture] public class SyncADONetTest { [NUnit.Framework.Test] public void test() { Console.WriteLine("test"); var sqlConnection = new SqlConnection(ConfigurationManager.AppSettings["Test"]); sqlConnection.Open(); var cmd = new SqlCommand(); cmd.Connection = sqlConnection; Stopwatch sw = new Stopwatch(); sw.Start(); for (var i = 0; i < 1000; i++) { cmd.CommandText = "INSERT INTO Test (UserName) VALUES ('" + "user" + i.ToString() + "')"; cmd.ExecuteNonQuery(); } sw.Stop(); var end = sw.ElapsedMilliseconds; Console.WriteLine("同步用時:{0}", end); sqlConnection.Close(); var sqlConnection2 = new SqlConnection(ConfigurationManager.AppSettings["Test"]); sqlConnection2.Open(); sw.Reset(); sw.Start(); for (var i = 0; i < 1000; i++) { var cmd2 = new SqlCommand(); cmd2.Connection = sqlConnection2; cmd2.CommandText = "INSERT INTO Test (UserName) VALUES ('" + "user" + i.ToString() + "')"; cmd2.BeginExecuteNonQuery(ir => { SqlCommand icmd = ir.AsyncState as SqlCommand; icmd.EndExecuteNonQuery(ir); }, null); } sw.Stop(); var end2 = sw.ElapsedMilliseconds; Console.WriteLine("異步用時:{0}", end2); sqlConnection.Close(); } } }
測試結果:測試
參考:https://technet.microsoft.com/zh-cn/library/zw97wx20(v=vs.100).aspxspa