如何使SqlConnection超时更快

Blu*_*kMN 15 .net c# sql-server sql-server-2005

我正在使用带有SqlClient.SqlConnection的SQL连接字符串,并在字符串中指定Connection Timeout = 5,但它仍然等待30秒才返回失败.如何让它放弃并快速返回?我在一个快速的本地网络上,不想等待30秒.未打开的服务器需要30秒才能失败.这只是一个快速的实用程序,它将始终只在本地网络上运行.

编辑:对不起,如果我不清楚.我希望SqlConnection.Open更快地失败.希望这可以从我想要更快失败的服务器被关闭的事实中推断出来.

编辑:似乎设置有时只会失败.就像它知道服务器的IP地址,并使用TCP/IP与它通信(非本地)但不能联系该地址的SQL Server?我不确定该模式是什么,但我在本地连接SQL Server停止时没有看到问题,并且在尝试连接到不存在的服务器时我没有看到它.我曾尝试联系Windows 2008防火墙阻止SQL Server的服务器时看到过它.

Blu*_*kMN 11

它看起来像所有被耽搁了很长时间可以解决的情况下,多少通过尝试这样的直接套接字连接迅速更多:

foreach (string svrName in args)
{
   try
   {
      System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient(svrName, 1433);
      if (tcp.Connected)
         Console.WriteLine("Opened connection to {0}", svrName);
      else
         Console.WriteLine("{0} not connected", svrName);
      tcp.Close();
   }
   catch (Exception ex)
   {
      Console.WriteLine("Error connecting to {0}: {1}", svrName, ex.Message);
   }
}
Run Code Online (Sandbox Code Playgroud)

我将使用此代码检查服务器是否响应SQL Server端口,并且仅尝试打开连接.我认为(基于其他人的经验)即使在这个级别也会有30秒的延迟,但我得到一条消息,说机器"立即主动拒绝连接".

编辑:如果机器不存在,它也会马上告诉我.我找不到30秒的延误.

编辑:网络上但未关闭的机器仍然需要30秒才能失败.然而,防火墙的机器失败得更快.

编辑:这是更新的代码.我觉得关闭套接字比删除线程更干净:

static void TestConn(string server)
{
   try
   {
      using (System.Net.Sockets.TcpClient tcpSocket = new System.Net.Sockets.TcpClient())
      {
         IAsyncResult async = tcpSocket.BeginConnect(server, 1433, ConnectCallback, null);
         DateTime startTime = DateTime.Now;
         do
         {
            System.Threading.Thread.Sleep(500);
            if (async.IsCompleted) break;
         } while (DateTime.Now.Subtract(startTime).TotalSeconds < 5);
         if (async.IsCompleted)
         {
            tcpSocket.EndConnect(async);
            Console.WriteLine("Connection succeeded");
         }
         tcpSocket.Close();
         if (!async.IsCompleted)
         {
            Console.WriteLine("Server did not respond");
            return;
         }
      }
   }
   catch(System.Net.Sockets.SocketException ex)
   {
      Console.WriteLine(ex.Message);
   }
}
Run Code Online (Sandbox Code Playgroud)