c# - Windows 服务不会停止/启动

标签 c#

我正在使用以下代码片段来停止服务。但是,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);
}

关于c# - Windows 服务不会停止/启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4016278/

相关文章:

c# - WPF。在后面的代码中使用 xaml 中的按钮样式

c# - 如何从 asp.net 中的 .cs 文件动态更改 Bootstrap 进度条

c# - 将禁用的 TextBox 的 ForeColor 设置为与其在 C# 中的 BackColor 相同

使用 PictureBox 的 C# 碰撞检测

c# - 有没有办法在 C# 应用程序中保持电子邮件 session ?

c# - 如何获取类内对象的变量名?

c# - 如何配置 log4net 以在 Debug模式下打印到控制台

c# - NUnit值得学习吗?

c# - 检测新应用并在面板中运行

c# - ContinueWith TaskContinuationOptions.OnlyOnFaulted 似乎没有捕获到从启动的任务中抛出的异常