How can I register that a Windows service is shutting down due to a system shutdown?

I have a diagnostic version of the service that logs as many as possible in the OnStart () and OnStop () methods.

One event that I cannot perform is when the computer is physically restarted. My logging function usually writes its output to a table in the database, but when it is not available, it is sent to EventLog.

When I restart, my service is not registered either in the table or in the EventLog.

It seems to me that I will not be able to send a message to the table, since SQL Server is in the process of shutting down, but it also seems that due to a synchronization problem, EventLog can also be closed before the service can write there by default.

In case of shutdown, MSSQLSERVER reports an informational message in EventLog:

SQL Server shuts down due to system shutdown. This is an informational message. No user action required.

Is there a way to do something like this for my service?

+4
source share
4 answers

You can specify the dependencies of your Windows Service so that it requires a different service. If you specify a dependency on the EventLog service, then Windows will wait until your service is disconnected before closing the event log.

http://kb2.adobe.com/cps/400/kb400960.html describes how to do this by changing several registry keys.

Go to HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Services and find the service you want to install the dependency for. Open the DependOnService key on the right side. If the selected service does not have the "DependOnService" key, then create it by right-clicking and select New> Multi-String Value. In the value field, enter the names of all the services that the current service will depend on. Each service name must be entered correctly and on a separate line.

+3
source

There is an OnShutdown method that you can override in your service. It will be called when the machine turns off. Write to the event log from this method, then call base.OnShutdown ().

+3
source

Capture SystemEvents.SessionEnding

In OnStart, you can capture it and process it.

like

Microsoft.Win32.SystemEvents.SessionEnding += new Microsoft.Win32.SessionEndingEventHandler(this.zomgRebootinglol); 
0
source

You can capture Windows events using SystemEvents-Class .

Also consider events . I think the event you are looking for is: SystemEvents :: PowerModeChanged event and / or SystemEvents :: SessionEnded

0
source

Source: https://habr.com/ru/post/1302268/


All Articles