测试数据库服务器是否可用

在Sql连接字符串中设置Connect Timeout无效,只能通过Socket去判断

代码如下:

        /// <summary>
        
/// 测试数据库服务器是否可用
        
/// </summary>
        
/// <param name="ip">服务器IP</param>
        
/// <param name="port">服务器端口,一般是1433</param>
        
/// <param name="timemout">设置超时时间,毫秒</param>
        
/// <returns>如果数据库可用返回true,否则返回false</returns>
        static bool TestConn(string ip, int port, int timemout)
        {
            
using (TcpClient client = new TcpClient())
            {

                ManualResetEvent mre 
= new ManualResetEvent(false);
                client.BeginConnect(ip, port, 
delegate(IAsyncResult res)
                {
                    
if (client.Connected)
                    {
                        mre.Set();
                        Console.WriteLine(
"123");
                    }
                }, 
null);
                ThreadPool.QueueUserWorkItem(
delegate(object obj) { Thread.Sleep(timemout); mre.Set(); });
                mre.WaitOne();
                
if (!client.Connected)
                {
                    
return false;
                }
                
return true;
            }
        }

测试代码:

 
            DateTime begin = DateTime.Now;
            Console.WriteLine(TestConn(
"192.168.1.99"14332000));
            Console.WriteLine(DateTime.Now.Subtract(begin).TotalSeconds);
 

 

posted @ 2011-07-25 11:36  再快一点  阅读(363)  评论(0编辑  收藏  举报