主要是三种情况:
1、sqlcommand执行超时;
2、sqlconnection执行超时;
3、数据库掉线TCP连接不上,针对第三种情况代码如下:
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."); }
标签:connectSuccess,sw,SQLServer,不上,timeout,Stopwatch,new,连接 From: https://www.cnblogs.com/rooobins/p/17125736.html