2010-10-25 239 views
5

我正在使用以下代码片段来停止服务。但是,Console.Writeline声明表明服务正在运行。为什么服务不会停止?Windows服务不会停止/启动

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()); 
    } 
} 
+0

在哪里使用的用户名和密码? – Aliostad 2010-10-25 15:47:46

+0

我在更改与服务关联的帐户和密码的代码中进一步使用它。 – xbonez 2010-10-25 15:50:01

回答

5

您需要拨打sc.Refresh()刷新状态。有关更多信息,请参阅http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.stop.aspx

此外,服务停止可能需要一些时间。如果该方法立即返回,它可能改变你的关机弄成这样有用:

// 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); 
} 
+0

工程。谢谢一堆! – xbonez 2010-10-25 15:51:57

1

尝试调用:

sc.Refresh(); 

您的来电前的状态。

2

在检查状态之前调用sc.Refresh()。它也可能需要一些时间来停止。

0

您是否拥有停止/启动服务的正确权利?

你以什么账号运行你的控制台应用程序?管理员权限?

您是否试过sc.WaitForStatus?这可能是服务停止,但不是您到达您的writeline时。

1

我相信你应该使用sc.stop然后刷新 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()); 
1

尝试以下操作:

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