gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:42:14 30 4
gpt4 key购买 nike

我有最简单的 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com