首先連接超時分為三種,
TCP Connection to SQL Server -> SqlConnection.Open -> SqlCommand.Execute
先說第二種超時,sqlcon打開,我們不能直接設置connectiontimeout,只能在連接字符串中設置:
Data Source=server;Initial Catalog=databaseUser Id=username;Password=password;Connect Timeout=3
此設置默認時間為妙,而不是毫秒。默認是三十秒,可以設置為3秒。
注意:此處不能設置conn.open()超時回應的時間。因為conn.open(),不只是sqlserver響應嘗試連接數據庫的時間,其中還有Tcp請求的時間.所以如果
你設置Connect Timeout=2,在連接不到server的情況下,報告超時的時間也遠遠超過2s。因為此處設置的只是在sqlserver必須回應一個連接
嘗試的時間。但是如果你根本就無法連接到server,這個設置也就無從談起。
第三種超時比較簡單,就是sql語句在數據庫中的執行時間。通過 SqlCommand.CommandTimeout就可以進行設置。
第一種超時就是tcp請求的超時,這個是沒有辦法通過設置屬性實現的。但是我們必須要控制它,因為一個連接可能幾十秒之后才會回應你超時
http://improve.dk/controlling-sqlconnection-timeouts/
public static class SqlExtensions { public static void QuickOpen(this SqlConnection conn, int timeout) { // We'll use a Stopwatch here for simplicity. A comparison to a stored DateTime.Now value could also be used Stopwatch sw = new Stopwatch(); bool connectSuccess = false; // Try to open the connection, if anything goes wrong, make sure we set connectSuccess = false Thread t = new Thread(delegate() { try { sw.Start(); conn.Open(); connectSuccess = true; } catch { } }); // Make sure it's marked as a background thread so it'll get cleaned up automatically t.IsBackground = true; t.Start(); // Keep trying to join the thread until we either succeed or the timeout value has been exceeded while (timeout > sw.ElapsedMilliseconds) if (t.Join(1)) break; // If we didn't connect successfully, throw an exception if (!connectSuccess) throw new Exception("Timed out while trying to connect."); } }