开发者

Windows Service won't stop/start

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开发者_StackOverflow中文版(sc.Status.ToString());
    }
}


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);
}


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


Try calling:

sc.Refresh();

before your call to Status.


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());


Try the following:

 while (sc.Status != ServiceControllerStatus.Stopped)
 {
     Thread.Sleep(1000);
     sc.Refresh();
 }


Do you have the correct rights to stop/start a service?

What account are you running your console app as? Admin rights?

Have you tried sc.WaitForStatus? It may be that the service is stopping but not by the time you reach your writeline.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜