Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I restart a windows service programmatically in .NET

How can I restart a windows service programmatically in .NET?
Also, I need to do an operation when the service restart is completed.

like image 440
Nemo Avatar asked Sep 21 '09 13:09

Nemo


People also ask

How can a Windows service programmatically restart itself?

Solution 4 1) Go to Services and look at the properties of your installed service. Go to Recovery and set the First Failure pick list to "Restart the Service". Set the Reset fail count after text box to 0 if you want to be able to restart it multiple times in a day.

How do I rerun a service?

Press the Windows Key + R, type in services. msc and press Enter. Locate the Service that you want to start, stop, or restart. Right-click on that Service and click on Start, Stop, or Restart.


2 Answers

Take a look at the ServiceController class.

To perform the operation that needs to be done when the service is restarted, I guess you should do that in the Service yourself (if it is your own service).
If you do not have access to the source of the service, then perhaps you can use the WaitForStatus method of the ServiceController.

like image 32
Frederik Gheysels Avatar answered Sep 28 '22 09:09

Frederik Gheysels


This article uses the ServiceController class to write methods for Starting, Stopping, and Restarting Windows services; it might be worth taking a look at.

Snippet from the article (the "Restart Service" method):

public static void RestartService(string serviceName, int timeoutMilliseconds) {   ServiceController service = new ServiceController(serviceName);   try   {     int millisec1 = Environment.TickCount;     TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);      service.Stop();     service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);      // count the rest of the timeout     int millisec2 = Environment.TickCount;     timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2-millisec1));      service.Start();     service.WaitForStatus(ServiceControllerStatus.Running, timeout);   }   catch   {     // ...   } } 
like image 170
Donut Avatar answered Sep 28 '22 10:09

Donut