0

我正在尝试监视 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");

    }
4

0 回答 0