I have developed a windows service in vb.net (VS2017, target .net framework 4.5).
The windows service do automatically sql-server backups (timer based), delete old backup files, read and write a .ini file and send emails in some situations and - of curse - write to the event log. The Service has to run on a windows server 2019 (standard).
Anything works as expected - except the handling of the OnShutdown() event, that drives me crazy, as it is a "moving target".
If the server is shut down (normal case should be "restart"), I want to:
- log in the event log
- write in a .ini
- send an email
My code zu OnShutdown():
Protected Overrides Sub OnShutdown()
cModul = "OnShutdown()"
ProtokollSchreiben("Der Server wird heruntergefahren...", Typ_Warning)
'
DebugProtokollSchreiben("Timer stoppen und anhalten...", Typ_Warning)
MyTimer.Stop()
MyTimer.Enabled = False
DebugProtokollSchreiben("Timer gestoppt und angehalten...", Typ_Warning)
DebugProtokollSchreiben("Der Server wird heruntergefahren...", Typ_Warning)
DebugProtokollSchreiben("Vor schreiben .ini...", Typ_Warning)
cIniFile.WriteInteger("WindowsService", "ServerWurdeGebooted", 1)
DebugProtokollSchreiben("Nach schreiben .ini...", Typ_Warning)
DebugProtokollSchreiben("Vor MailversandServerReboot...", Typ_Warning)
MailversandServerReboot()
cModul = "OnShutdown()"
DebugProtokollSchreiben("Nach MailversandServerReboot...", Typ_Warning)
'
MyBase.OnShutdown()' call “original event”
End Sub
Notes:
I set:
Me.CanShutdown = True
in the designer code and write the actual value at startup in the event log (CanShutdown is set to true at runtime).
In ProtokollSchreiben() and DebugProtokollSchreiben() only log entries are written.
In MailversandServerReboot() an email is sent over SMTP (this works in other parts of the service without problems).
Behavior:
- sometimes the event (OnShutdown() is called, sometimes not
- if it is called, mostly, the last event in the event log is "Vor schreiben .ini..." (= before write in the .ini file)
- -> whereby the .ini in this cases sometimes is updated (although the next log entry "Nach schreiben .ini..." is not written to the event log), sometimes not
I have searched the internet and read this SO-Links:
detect shutdown in window service
Windows Service does seem to do nothing OnShutdown()
Can a Windows Service take hours to shutdown gracefully?
As far, as I have seen, I should have about 20 Seconds time to do something in OnShutDown().
To write the event log and the .ini should not take a single second....
Maybe, to send the email (in function "MailversandServerReboot()") could take a longer time or maybe the email can't be sent as other (needed) services are down, when OnShutdown() is triggered...
But, I don't understand, that the event sometimes is called, sometimes not and if it is called, that mostly the entry "Nach schreiben .ini..." is not written to the event log.
Thanks for any hint :-)