I have inherited a Windows service written in C#. Under rare conditions it fails badly. However, it isn\'t at all clear how to fail well. Ross Bennett states the problem e
I don't know if there is a (non-P/Invoke) equivalent for this, but the WinAPI way seems to be to call SetServiceStatus
with a value of SERVICE_STOPPED
and then wait for the SCM to shut you down. As a positive side-effect, it logs the failure of your service into the event log.
Here are some quotes from the relevant part of the documentation:
If a service calls SetServiceStatus with the dwCurrentState member set to SERVICE_STOPPED and the dwWin32ExitCode member set to a nonzero value, the following entry is written into the System event log:
[...]
terminated with the following error: [...] The following are best practices when calling this function:
[...]
- If the status is SERVICE_STOPPED, perform all necessary cleanup and call SetServiceStatus one time only. This function makes an LRPC call to the SCM. The first call to the function in the SERVICE_STOPPED state closes the RPC context handle and any subsequent calls can cause the process to crash.
- Do not attempt to perform any additional work after calling SetServiceStatus with SERVICE_STOPPED, because the service process can be terminated at any time.
PS: In my opinion, if network resources are unavailable, the service should not stop but continue running, waiting for the resources to become available. Temporary network outages can happen, and they should not require manual intervention from the system administrator once the network is back up.