代码之家  ›  专栏  ›  技术社区  ›  Ayush

Windows服务不会停止/启动

c#
  •  5
  • Ayush  · 技术社区  · 15 年前

    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());
        }
    }
    
    6 回复  |  直到 9 年前
        1
  •  6
  •   Pieter van Ginkel    15 年前

    你需要打电话 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);
    }
    
        2
  •  2
  •   Den    15 年前

    在检查状态之前调用sc.Refresh()。可能还需要一段时间才能停止。

        3
  •  1
  •   Chris Wallis    15 年前

    尝试呼叫:

    sc.Refresh();
    

        4
  •  1
  •   Kirit Chandran    15 年前

    我认为你应该先使用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());
    
        5
  •  1
  •   Tshilidzi Mudau Simon Müller    9 年前

    请尝试以下操作:

     while (sc.Status != ServiceControllerStatus.Stopped)
     {
         Thread.Sleep(1000);
         sc.Refresh();
     }
    
        6
  •  0
  •   MattC    15 年前

    您有停止/启动服务的正确权限吗?

    你用什么帐户运行你的控制台应用程序?管理权限?

    你试过怀特福斯塔斯警长吗?可能是服务停止了,但在您到达writeline时还没有。