如何在我的Windows服务之前启动MYSQL服务

时间:2011-07-16 04:14:18

标签: c# windows-services

我有运行的Windows服务程序,有时会抛出有关系统空引用的异常。经过我的调查,这是由于MySQL连接无法建立,因为启动计算机时MySql实例尚未启动。如何解决这个问题???

提前致谢

3 个答案:

答案 0 :(得分:2)

您可以在Windows中设置每项服务的依赖关系。

您可以进入控制面板 - >管理工具 - >服务(或从命令行运行'services.msc')。通过双击任何服务并转到“依赖关系”选项卡,您可以看到每个服务所依赖的内容。

您的服务依赖于MySql服务,因此MySql应该位于依赖项列表中。

您可以向依赖项添加项目,以下是如何执行此操作的说明:

https://serverfault.com/questions/24821/how-to-add-dependency-on-a-windows-service-after-the-service-is-installed

答案 1 :(得分:1)

答案 2 :(得分:1)

如果您想自己做而没有依赖性,请尝试以下代码

//Check if service is running
ServiceController mysqlServiceController = new ServiceController();
mysqlServiceController.ServiceName = "MySql";
var timeout = 3000;

//Check if the service is started
if (mysqlServiceController.Status == System.ServiceProcess.ServiceControllerStatus.Stopped
                || mysqlServiceController.Status == System.ServiceProcess.ServiceControllerStatus.Paused)
{
      mysqlServiceController.Start();

      try
      {
           //Wait till the service runs mysql
           ServiceController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, new TimeSpan(0, timeout, 0));
      }
      catch (System.ServiceProcess.TimeoutException)
      {
          //MessageBox.Show(string.Format("Starting the service \"{0}\" has reached to a timeout of ({1}) minutes, please check the service.", mysqlServiceController.ServiceName, timeout));
      }
}