2016-04-24 34 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()它被返回到池但没有被销毁,只是等待别人再次使用它。