Search code examples
c#windows-servicestopshelf

How to delay Topshelf service stopping during OS shutdown


We have a windows service created with Topshelf (4.0.1). Is there any way how to delay it's stopping during operating system shutdown?

I know it's pretty problematic desire so an explanation: Let's say that we have win service what needs some additional time during shutdown (some tasks have to be completed correctly and now we have no way how to perform it faster).

It's possible to delay standard service stop (performed e.g. by Powershell Stop-Service cmdlet or so...) by calling RequestAdditionalTime() in the service OnStop(). It all works well when stopping the service in such "standard" way... But RequestAdditionalTime() cannot be used during system shutdown (i.e. windows service OnShutdown()). Because of that I've implemented this SO answer approvach in classical windows service and 3:20 delay was achieved by that (that's what we need).

But mentioned SO answer solution (hack, better to say) doesn't work with Topshelf.

Is there any way how to do it with Topshelf?


Solution

  • It should be possible to register a custom EnvironmentBuilder (using extension method UseEnvironmentBuilder on a HostConfigurator instance) that returns a customized implementation of the HostEnvironment interface. Custom implementation of the HostEnvironment.CreateServiceHost method can return any implementation of Host you need (e.g. a Host that Run()s your ServiceBase).

    You can reuse implementation of other HostEnvironment / Host methods by forwarding calls to WindowsHostEnvironment and WindowsServiceHost classes, respectively. WindowsHostEnvironment instance can be simply created in your custom EnvironmentBuilder constructor (and passed into custom HostEnvironment).