2010-10-25 235 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(); 
}