Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Service won't stop/start

Tags:

c#

I'm using the following code fragment to stop a service. However, both the Console.Writeline statements indicate the service is running. Why won't the service stop?

class Program
{
    static void Main(string[] args)
    {
        string serviceName = "DummyService";
        string username = ".\\Service_Test2";
        string password = "Password1";

        ServiceController sc = new ServiceController(serviceName);

        Console.WriteLine(sc.Status.ToString());

        if (sc.Status == ServiceControllerStatus.Running)
        {
            sc.Stop();
        }

        Console.WriteLine(sc.Status.ToString());
    }
}
like image 544
xbonez Avatar asked Oct 25 '10 15:10

xbonez


5 Answers

You need to call sc.Refresh() to refresh the status. See http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.stop.aspx for more information.

Also, it may take some time for the service to stop. If the method returns immediately, it may be useful to change your shutdown into something like this:

// Maximum of 30 seconds.

for (int i = 0; i < 30; i++)
{
    sc.Refresh();

    if (sc.Status.Equals(ServiceControllerStatus.Stopped))
        break;

    System.Threading.Thread.Sleep(1000);
}
like image 75
Pieter van Ginkel Avatar answered Nov 13 '22 12:11

Pieter van Ginkel


Call sc.Refresh() before checking status. It also might take some time to stop.

like image 37
Den Avatar answered Nov 13 '22 13:11

Den


Try calling:

sc.Refresh();

before your call to Status.

like image 40
Chris Wallis Avatar answered Nov 13 '22 11:11

Chris Wallis


I believe you should use sc.stop and then refresh http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.refresh(VS.80).aspx

   // If it is started (running, paused, etc), stop the service.
// If it is stopped, start the service.
ServiceController sc = new ServiceController("Telnet");
Console.WriteLine("The Telnet service status is currently set to {0}", 
                  sc.Status.ToString());

if  ((sc.Status.Equals(ServiceControllerStatus.Stopped)) ||
     (sc.Status.Equals(ServiceControllerStatus.StopPending)))
{
   // Start the service if the current status is stopped.

   Console.WriteLine("Starting the Telnet service...");
   sc.Start();
}  
else
{
   // Stop the service if its status is not set to "Stopped".

   Console.WriteLine("Stopping the Telnet service...");
   sc.Stop();
}  

// Refresh and display the current service status.
sc.Refresh();
Console.WriteLine("The Telnet service status is now set to {0}.", 
                   sc.Status.ToString());
like image 1
Kirit Chandran Avatar answered Nov 13 '22 12:11

Kirit Chandran


Try the following:

 while (sc.Status != ServiceControllerStatus.Stopped)
 {
     Thread.Sleep(1000);
     sc.Refresh();
 }
like image 1
A_Nabelsi Avatar answered Nov 13 '22 12:11

A_Nabelsi