繁体   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