Reputation: 130
I have simplest possible windows service.
I need service to run under Local System account.
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.
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 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();
}
}
}
and Main Entry:
using System.ServiceProcess;
namespace SimplestService
{
class Program
{
static void Main(string[] args)
{
ServiceBase.Run(new MyService());
}
}
}
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
Upvotes: 4
Views: 3604
Reputation: 545
Microsoft Windows has added an option called Fast Startup
which does not actually shutdown the computer.
As noted in the Fast Startup
setting description, Restart
isn't affected. This is why the Restart
triggers OnShutdown
and Shutdown
does not.
Turning off Fast Startup
will trigger OnShutdown
for both Restart
and Shutdown
.
Upvotes: 6
Reputation: 493
From what I researched, the OnShutdown method is called when the OS is shutdown, but there is there is a strict time limit, but i believe the local system services are terminated even before this time limit so that OS shutdown time is fast. This might explain why domain account are shutdown slower. Windows has introduced a PreShutdown event to handle this. Try the link below, it has more information on this https://www.atomia.com/2011/11/16/how-to-process-the-preshutdown-event-in-a-managed-windows-service/
Upvotes: 3