2016-04-24 45 views
0

我檢查連接可用的代碼:如何減少打開連接的等待時間?

SqlConnection objConnection = new SqlConnection(string.Concat(connectionString)); 
     try 
     { 
      objConnection.Open(); // this line make wait time if connection not available 
      objConnection.Close(); 
      SqlConnection.ClearAllPools(); 
      return true; 
     } 
     catch 
     { 
      return false; 
     } 

當連接不可用,這需要很長的時間來回答。如何能減少呢?

+0

如果您通過TCP協議進行連接,您可以嘗試將服務器配置爲響應簡單的ping並在啓動真正的TCP連接之前使用該協議。我假設你的客戶端有一個網絡連接。 – rene

+0

我沒有訪問配置服務器。 – shahroz

回答

1

你可以先嚐試Ping服務器。在我的盒子上,ping只需5秒就可以斷定服務器不可達。它利用該功能的最簡單的代碼顯示在這個片段:

if(new System.Net.NetworkInformation.Ping().Send("Your servername here").Status != 
     System.Net.NetworkInformation.IPStatus.TimedOut) 
{ 
    // server reachable, try a real SQL Server connection now 
    SqlConnection objConnection = new SqlConnection(connectionstring); 
    try 
    { 
     objConnection.Open(); // this line make wait time if connection not available 
     objConnection.Close(); 
     // not sure why you would want this 
     // only use if you want worse performance 
     // SqlConnection.ClearAllPools(); 
     return true; 
    } 
    catch 
    { 
     return false; 
    } 
} 
else 
{ 
    return false; // PING failed 
} 

系統管理員可能會禁用/塊ICMP流量,此選項可能並不適用於所有的服務器工作。

1

您可以檢查SQL連接這種方式,如果要連接到您的SQL Server這不會需要很長時間

 SqlConnection objConnection = new SqlConnection(string.Concat(connectionString)); 
     try 
     { 
      objConnection.Open(); 
     } 
     catch {} 

     if (objConnection != null && objConnection.State == ConnectionState.Open) 
     { 
      try 
      { 
       objConnection.Close(); 
      } 
      catch {} 
      return true; 
     } 
     else if (objConnection != null && objConnection.State == ConnectionState.Closed) 
     { 
      try 
      { 
       objConnection.Close(); 
      } 
      catch {} 
      return false; 
     } 
+0

objConnection.State是關閉的,因爲我不打開它! – shahroz

+0

沒有打開你沒有選擇檢查,如果你嘗試打開它並失敗,那麼肯定會花費時間,因爲它會嘗試重新連接,然後報告你無法打開 – Mostafiz

+0

如何減少這段時間(它會嘗試重新連接)?可能嗎? – shahroz

1

請勿ClearAllPools!連接池專門用於使連接更高效。當您使用Open()時,將使用池中的連接(如果有連接)。當你Close()它被返回到池但沒有被銷燬,只是等待別人再次使用它。