问题
I have the windows service program which runs and sometime throw exception about system null reference. After my investigation, this is due to MySQL connection cannot establish due to MySql instance not up yet when startup computer. How to solve this problems???
thanks in advance
回答1:
You can set in Windows the dependencies of each service.
You can go into Control Panel -> Administrative Tools -> Services (or run 'services.msc' from the command line). By double clicking any of the services and going to the Dependencies tab you can see what each service relies on.
Your service relies on the MySql service, so MySql should be in the dependencies list for it.
You can add items to the dependencies, here is a description of how to do this:
https://serverfault.com/questions/24821/how-to-add-dependency-on-a-windows-service-after-the-service-is-installed
回答2:
This article can give you a hint on how code service dependencies:
http://bloggingabout.net/blogs/jschreuder/archive/2006/12/07/How-to_3A00_-Code-Service-Dependencies.aspx
回答3:
Try the following code if you want to do it by yourself without dependencies
//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));
}
}
来源:https://stackoverflow.com/questions/6715277/how-to-start-the-mysql-service-before-my-windows-service