簡體   English   中英

Windows服務不會停止/啟動

[英]Windows Service won't stop/start

我正在使用以下代碼片段來停止服務。 但是, Console.Writeline語句都表明服務正在運行。 為什么服務不會停止?

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

您需要調用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);
}

在檢查狀態之前調用sc.Refresh()。 它也可能需要一些時間才能停止。

試着打電話:

sc.Refresh();

在你打電話給狀態之前。

我相信你應該使用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());

請嘗試以下方法:

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

您是否擁有停止/啟動服務的正確權利?

您運行控制台應用的帳戶是什么? 管理權限?

你試過sc.WaitForStatus嗎? 可能是服務正在停止,但是當你到達你的寫信線時卻沒有。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM