通过保持连接打开来监视和SQL Server连接

时间:2012-07-11 17:48:22

标签: c# sql-server

我正在尝试监控SQL Server数据库连接,我遇到了问题,或者它的行为与设计有关。
我想这样做:

Open Connection
   Write "Open"
Leave it open for 1 minute (using System.Threading.Thread.Sleep)
   If the connection drops during this time write "Down" to the console
Close the connection
   Write "Closed" to the console
Repeat forever

所以我的SQL Express服务启动了,我启动了我的代码

  

打开
  封闭式
  打开
  关闭

(两次之间有适当的时间) 然后我再次看到“打开”后,我停止了我的SQL Express服务,接下来的几行仍然是

  

打开
  封闭式
  打开
  关闭

现在,如果我在SQL Express服务停止时重新启动程序,那么我会得到正确的例外 这是我的代码。

   static void Main(string[] args)
    {
        //
        string strConnectionString;
        string strEnabled;
        string strPath;
        strConnectionString = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\GlobalNet Direct\\DatabaseMonitor", "ConnectionString", false).ToString();
        strEnabled = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\GlobalNet Direct\\DatabaseMonitor", "Enabled", false).ToString();
        strPath = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\GlobalNet Direct\\DatabaseMonitor", "LogPath", false).ToString(); 
        do
        {
            strEnabled = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\GlobalNet Direct\\DatabaseMonitor", "Enabled", false).ToString(); 


            //System.Threading.Thread.Sleep(15000);


            SqlConnection myConnection = new SqlConnection(strConnectionString);

            try
            {
                myConnection.Open();

                Console.WriteLine(myConnection.State.ToString());
                System.Threading.Thread.Sleep(1000);
            }
            catch (Exception)
            {
                Console.WriteLine("Down");

            }
            try
            {
                if (myConnection.State.ToString() == "Open")
                {
                    myConnection.Close();
                    System.Threading.Thread.Sleep(1000);
                    Console.WriteLine(myConnection.State.ToString());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());

            }
        }while (strEnabled == "True");

    }

0 个答案:

没有答案