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());
}
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With