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 サービスを開始したら、取得したコードを開始します
オープン
クローズ
オープン
クローズ
(適切な時間間隔で)次に、「Open」が再び表示された直後に、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");
}