How can I restart a windows service programmatically in .NET?
Also, I need to do an operation when the service restart is completed.
private void RestartWindowsService(string serviceName)
{
ServiceController serviceController = new ServiceController(serviceName);
try
{
if ((serviceController.Status.Equals(ServiceControllerStatus.Running)) || (serviceController.Status.Equals(ServiceControllerStatus.StartPending)))
{
serviceController.Stop();
}
serviceController.WaitForStatus(ServiceControllerStatus.Stopped);
serviceController.Start();
serviceController.WaitForStatus(ServiceControllerStatus.Running);
}
catch
{
ShowMsg(AppTexts.Information, AppTexts.SystematicError, MessageBox.Icon.WARNING);
}
}
You can set a service to restart after failure. So a restart can be forced by throwing an exception.
Use recovery tab on service properties.
Be sure to use reset fail count property to prevent service stopping altogether.
Call Environment.Exit
with an error code greater than 0, which seems appropriate, then on install we configure the service to restart on error.
Environment.Exit(1);
I have done same thing in my Service. It is working fine.
How about
var theController = new System.ServiceProcess.ServiceController("IISAdmin");
theController.Stop();
theController.Start();
Don't forget to add the System.ServiceProcess.dll to your project for this to work.