【问题标题】:Can a Windows service stop itself?Windows 服务可以自行停止吗?
【发布时间】:2012-07-30 23:54:18
【问题描述】:

我有一个启动类型为自动的 Windows 服务,但我想在服务启动时进行一些检查,并在这些检查失败时让服务自动停止。

我该怎么做?我的服务是用 C# 编写的。

【问题讨论】:

    标签: c# windows windows-services


    【解决方案1】:

    您可以在 ServiceBase 类上调用 Stop 方法。详情请见msdn

    【讨论】:

    • 这不是一个无效的场景,因为堆栈将从 OnStop 展开回到仍在运行的服务? If the service reports to the SCM that the service has stopped before all threads have exited, it is possible that the SCM will interpret this as a contradiction. This might result in a state where the service cannot be stopped or restarted.docs.microsoft.com/en-us/windows/win32/services/…
    • 它确实有效,@andrew.rockwell。调用OnStop 并不意味着服务会在所有线程退出之前报告它已经停止。您是否阅读了我的回答中的 msdn 链接?
    【解决方案2】:

    您可以使用ServiceController 并调用.stop。

    ServiceController sc= new ServiceController(service);
    sc.Stop();
    

    【讨论】:

      猜你喜欢
      • 2020-11-24
      • 1970-01-01
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多