J'ai une méthode pour vérifier et m'assurer que mon serveur SQL est en ligne, que j'utilise dans certaines parties sensibles de mon code.Comment puis-je vérifier si le serveur SQL est actif?
Bien que cela fonctionne bien, je remarque qu'il faut jusqu'à 20ms pour fonctionner, et je me demandais si quelqu'un connaît une meilleure façon de vérifier SQL Server pour assurer son up and kick.
Voici mon code existant.
[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;
}
20ms est sacrément rapide; est-ce une partie significative de votre page fois, ou appelez-vous cela énormément? –
20ms ne semble pas si mal. Considérez, vous faites une connexion, obtenez une réponse, et colmatez la connexion - partout dans le réseau. Je pense que vous aurez du mal à faire quelque chose plus vite ... mais je peux me tromper. – Nate
20 ms n'est pas très long, surtout si vous êtes sur le réseau. –