【问题标题】:Windows Service never call OnStop() method when shutdownWindows 服务在关机时从不调用 OnStop() 方法
【发布时间】:2018-12-15 00:43:38
【问题描述】:

我有最简单的 Windows 服务。

我需要服务才能在本地系统帐户下运行。

如果我从 SCM 启动/停止服务,一切正常,我的日志文本文件同时包含启动和停止事件,并且启动和停止事件都会自动显示在事件查看器中。

但是当我重新启动或关闭我的电脑时(在 Win 7 和 Win 10 上尝试过),如果服务以 身份运行,则永远不会调用 OnStop() 方法本地系统帐户。如果我将帐户更改为网络服务或任何其他本地/域帐户,则在重新启动/关闭 PC 之前调用 OnStop() 方法。

Windows 服务代码:

using System.IO;
using System.ServiceProcess;

namespace SimplestService
{
    class MyService : ServiceBase
    {
        private string path = "<pathtologfile>\\MyServiceLog.txt";

        public MyService()
        {
            this.ServiceName = "MyService";
            this.CanShutdown = true;
        }

        protected override void OnStart(string[] args)
        {
            using (StreamWriter sw = File.AppendText(path))
            {
                sw.WriteLine("MyService Started.");
            }
        }

        protected override void OnStop()
        {
            using (StreamWriter sw = File.AppendText(path))
            {
                sw.WriteLine("MyService Stopped.");
            }
        }

        protected override void OnShutdown()
        {
            OnStop();
        }
    }
}

和主要条目:

using System.ServiceProcess;

namespace SimplestService
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceBase.Run(new MyService());
        }
    }
}

为简单起见,我使用 SC 实用程序创建服务,尽管我尝试使用安装程序,甚至设置项目 (msi),但结果相同。

sc create MyService binPath= "<pathtoexe>\SimplestService.exe"
type= own start= auto DisplayName= Myservice

【问题讨论】:

    标签: c#


    【解决方案1】:

    Microsoft Windows 添加了一个名为Fast Startup 的选项,它实际上不会关闭计算机。

    Fast Startup 设置说明中所述,Restart 不受影响。这就是Restart 触发OnShutdownShutdown 不触发的原因。

    关闭Fast Startup 将为RestartShutdown 触发OnShutdown

    【讨论】:

      【解决方案2】:

      根据我的研究,当操作系统关闭时会调用 OnShutdown 方法,但是有严格的时间限制,但我相信本地系统服务甚至在这个时间限制之前就被终止了,因此操作系统关闭时间很快.这可以解释为什么域帐户关闭速度较慢。 Windows 引入了 PreShutdown 事件来处理此问题。 试试下面的链接,它有更多的信息 https://www.atomia.com/2011/11/16/how-to-process-the-preshutdown-event-in-a-managed-windows-service/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多