[C#]快速檢查Sql Server是否可以連線

  • 3819
  • 0

使用Sqlconnection.Open()去連線Sql Server時,若可以連線,不到1秒即可連線成功,
但是若Sql Server主機壞了,連線就會失敗,等很久才會有連線失敗的例外訊息出來,
嘗試設定ConnectionTimout=1,結果一點用都沒有!照樣等很久。
如何在1秒內快速的得知連線失敗,可以試試下面這個方法。

利用TcpClient嘗試連接Sql Server的port可以快速得知是否可以連線。
測試連線程式碼如下:

using System.Diagnostics;
using System.Net.Sockets;
using System.Threading;

private void button1_Click(object sender, EventArgs e)
{
   string ip = "192.168.1.10"; //SQL Server主機的IP位址。
   int port = 1433; //SQL Server的port預設是1433。

   Stopwatch sw = new Stopwatch();
   sw.Start();

   bool isConnection = TestConn(ip, port);

   sw.Stop();

   string message = string.Empty;
   if (isConnection)
   {
      message = "連線成功。 經過{0}秒。";
   }
   else
   {
      message = "連線失敗了! 經過{0}秒!";
   }

   double t = sw.ElapsedMilliseconds / 1000.0;
   MessageBox.Show(string.Format(message, t));

}




public bool TestConn(string ip, int port)
{
   try
   {
      using (TcpClient tc = new TcpClient())
      {
         IAsyncResult result = tc.BeginConnect(ip,port,null,null);
         DateTime start = DateTime.Now;

         do
         {
            SpinWait.SpinUntil(() => { return false; }, 100);
            if (result.IsCompleted) break;
         } 
         while (DateTime.Now.Subtract(start).TotalSeconds < 0.3);

         if (result.IsCompleted)
         {
            tc.EndConnect(result);
            return true;
         }

         tc.Close();

         if (!result.IsCompleted)
         {
            return false;
         }
					
      }
   }
   catch (Exception ex)
   {
      Console.WriteLine(ex.Message);
      throw;
   }

   return false;
}

測試結果
可以連線時:

無法連線時: