我有一种方法可以检查并确保我的 SQL 服务器在线,我在代码的某些连接敏感部分中使用了该方法。
虽然它运行良好,但我注意到它需要 20 毫秒才能运行,我想知道是否有人知道检查 SQL 服务器以确保其启动和启动的更好方法。
这是我现有的代码。
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public static bool IsSqlServerOnline(string connectionString)
{
#if DEBUG || DEBUG_SINGLE_CORE
Stopwatch sw = new Stopwatch();
sw.Start();
#endif
#if DEBUG || DEBUG_SINGLE_CORE
// This sould only occur of we are in the VSTS designer
if (string.IsNullOrEmpty(connectionString))
{
return false;
}
#endif
if ( !NetworkInterface.GetIsNetworkAvailable() )
{
return false;
}
if (string.IsNullOrEmpty(connectionString)) throw new ArgumentNullException("connectionString");
bool isSqlServerOnline = false;
SqlConnectionStringBuilder conString = new SqlConnectionStringBuilder(connectionString);
try
{
using (Ping p = new Ping())
{
string sqlSvr = conString.DataSource;
if (sqlSvr != null)
isSqlServerOnline = p.Send(sqlSvr).Status == IPStatus.Success;
}
}
catch (PingException)
{
isSqlServerOnline = false;
}
if ( isSqlServerOnline )
{
try
{
conString.ConnectTimeout = 3;
using (SqlConnection conn = new SqlConnection(conString.ToString()))
{
conn.Open();
isSqlServerOnline = true;
}
}
catch ( Exception )
{
isSqlServerOnline = false;
}
}
#if DEBUG || DEBUG_SINGLE_CORE
sw.Stop();
Trace.WriteLine(string.Format("IsSqlServerOnline: {0}", sw.ElapsedMilliseconds));
#endif
return isSqlServerOnline;
}