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: