Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to register for PreShutdown service events using .Net?

I've run into a situation where I deployed a .Net (C#) service on a Win 2008R2 server. The service has a dependency on MSMQ. At shutdown it needs to send a couple of quick messages before terminating. This works fine with manually triggered OnStop() events, but when the server is shutting down and the SCM calls OnShutdown() I'm finding that MSMQ has already shutdown and my service can't properly cleanup. My service only needs 2-5 seconds to do it's work.

I understand (now) that service dependencies only apply to startup, so that isn't helping. I spent some time today trying to figure out how to register my service to accept the newly (since Vista) available SERVICE_ACCEPT_PRESHUTDOWN events and work with the PreShutDownOrder feature (http://blogs.technet.com/b/askperf/archive/2008/02/04/ws2008-service-shutdown-and-crash-handling.aspx), but this isn't supported in the ServiceBase as implemented in the framework as far as I can tell.

I went down the path of trying to manually set it using the SetServiceStatus() function, but it doesn't appear to work.

_serviceHandle = this.ServiceHandle;
SERVICE_STATUS serviceStatus = new SERVICE_STATUS();
serviceStatus.currentState = (int)State.SERVICE_RUNNING;
serviceStatus.controlsAccepted = (int)(ControlsAccepted.SERVICE_ACCEPT_PRESHUTDOWN | ControlsAccepted.SERVICE_ACCEPT_STOP);
serviceStatus.waitHint = 0;
serviceStatus.checkPoint = 0;
bool setStatus = SetServiceStatus(_serviceHandle, ref serviceStatus);
int error = Marshal.GetLastWin32Error();

This returns an error status of 13 when you call GetLastError();

Any ideas for how to hook into the preshutdown service events?

like image 463
CactusPCJack Avatar asked Sep 15 '11 21:09

CactusPCJack


1 Answers

OK then the other alternative is to create/get/buy a C++ service that registers for the PreShutdown stuff and stops/shuts down your .Net services in your required order (and waits for them to actually exit).

It could either have its own shutdown order list/graph or build it using the existing Windows start up dependencies (ignoring services that it should not manage).

like image 189
anon Avatar answered Sep 21 '22 12:09

anon