c# - Windows 服务在关闭时从不调用 OnStop() 方法

标签 c#

我有最简单的 Windows 服务。

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

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

但是当我重新启动或关闭我的 PC 时(尝试使用 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

最佳答案

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

快速启动 设置说明中所述,重新启动 不受影响。这就是为什么 Restart 会触发 OnShutdownShutdown 不会。

关闭Fast Startup 将触发OnShutdown RestartShutdown

Power Options System Settings

关于c# - Windows 服务在关闭时从不调用 OnStop() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42697816/

相关文章:

c# - C#5.0 中的非阻塞 sleep (类似于 JavaScript 中的 setTimeout)

c# - RedisClient.Get<T> C# 与 ServiceStack.Redis 的性能

c# - ASP.net 页面文本区域中的文本剪切

c# - 获取筛选后的 DataGrid 中选定行的索引

c# - 在 c# 2.0 中阻止/重定向 IP 或没有主机文件的主机

c# - Prism:通过事件关闭对话

c# - NHibernate:具有通用枚举属性的映射类

c# - 将选定区域的文本复制到剪贴板

c# - Xamarin.Forms 中 StreamWriter 中的 ArgumentException

c# - 无法在 ASP.NET Core 操作筛选器中获取正确的 DbContext 引用