Windows服务从不关闭时调用OnStop()方法 [英] Windows Service never call OnStop() method when shutdown
问题描述
我有最简单的Windows服务.
I have simplest possible windows service.
我需要服务才能在本地系统帐户下运行.
I need service to run under Local System account.
如果我从SCM启动/停止服务,则一切正常,我的日志文本文件同时具有Start和Stop事件,并且Start和Stop事件都自动显示在事件查看器中.
If I start/stop service from SCM, everything works fine, my log text file has both Start and Stop events, and also both Start and Stop events are shown automatically in the event viewer.
但是当我重新启动或关闭计算机(尝试使用Win 7和Win 10)时,如果服务以运行,则不会调用 OnStop()方法.本地系统帐户.如果我将帐户更改为网络服务或任何其他本地/域帐户,则在PC重新启动/关闭之前将调用OnStop()方法.
But when I restart or shutdown my PC (tried with Win 7 and Win 10), OnStop() method is never called, if service runs as Local System account. If I change account to Network Service or any other Local/Domain account, OnStop() method is called before restart/shutdown of the PC.
Windows服务代码:
Windows service code:
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());
}
}
}
为简单起见,即使我尝试使用Installer甚至安装项目(msi),我也使用SC实用程序来创建服务,但是结果却相同.
For simplicity I've used SC utility to create service, even though I tried with Installer, even setup project (msi), but with same results.
sc create MyService binPath= "<pathtoexe>\SimplestService.exe"
type= own start= auto DisplayName= Myservice
推荐答案
Microsoft Windows添加了一个名为 Fast Startup
的选项,该选项实际上并未关闭计算机.
Microsoft Windows has added an option called Fast Startup
which does not actually shutdown the computer.
如快速启动
设置说明中所述,重新启动
不受影响.这就是为什么 Restart
触发 OnShutdown
而 Shutdown
不会触发的原因.
As noted in the Fast Startup
setting description, Restart
isn't affected. This is why the Restart
triggers OnShutdown
and Shutdown
does not.
关闭快速启动
将同时触发重新启动
和关闭
的 OnShutdown
.
这篇关于Windows服务从不关闭时调用OnStop()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!