我正在编写一个应用程序来自动重新启动 SQL 服务。基本上,这些是我正在做的步骤:
- 关闭申请
- 停止 SQL 服务
- 启动 SQL 服务
- 开始申请
我遇到的问题是启动应用程序。似乎应用程序在 SQL 服务之前启动,从而导致数据库连接错误。我正在以下几行检查服务的状态,但它仍然无法正常工作:
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
if (service.Status == ServiceControllerStatus.Stopped)
代码:
static void Main(string[] args)
{
PrintMessage("arg 0: " + args[0]);
PrintMessage("arg 1: " + args[1]);
PrintMessage("arg 2: " + args[2]);
Console.Title = "SQL Server Restart";
PrintMessage("Commencing SQL Server restart. Please wait. . .");
string serverInstance = args[0];
ServiceController service = new ServiceController(serverInstance);
try
{
if (service.Status == ServiceControllerStatus.Running)
{
PrintMessage("Checking server status");
TimeSpan timeout = TimeSpan.FromMinutes(5);
PrintMessage("Stoppping server");
service.Stop();
service.Refresh();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
if (service.Status == ServiceControllerStatus.Stopped)
{
PrintMessage("Starting server");
service.Start();
service.Refresh();
service.WaitForStatus(ServiceControllerStatus.Running);
if (service.Status == ServiceControllerStatus.Running)
{
PrintMessage("Server started");
//Restart application
if (args[2] == "False")
{
PrintMessage("Press any key to continue. . .");
Console.ReadKey();
Environment.Exit(0);
}
else
{
PrintMessage("Starting Application");
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = args[1];
info.WorkingDirectory = Path.GetDirectoryName(info.FileName);
Process process = new Process();
process.StartInfo.UseShellExecute = false;
Process.Start(info);
PrintMessage("Application started");
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Base Exception: " + ex.GetBaseException());
Console.WriteLine("Inner Exception: " + ex.InnerException);
Console.WriteLine(ex.Message);
}
PrintMessage("Press any key to continue. . .");
Console.ReadKey();
}