Reputation: 1191
I have created a Windows Service in VB.NET (VS2010) that executes a certain task every minute. When the service is being stopped, either manually by the user, or when the system is rebooted, what can I do to make sure the task is being finished properly before the service is actually terminated?
Upvotes: 1
Views: 3401
Reputation: 460018
You should override the Service's OnStop event.
' when stopping release the resources
Protected Overrides Sub OnStop()
ReleaseYourObjects()
End Sub
Here you should finish your task and release all resources that need to be released.
The constructor of the service will not be called again when it's restarted. Because of this, you should not use the constructor to perform startup processing, rather use the OnStart()
method to handle all initialization of your service, and OnStop()
to release any resources.
Reduced to your needs, it might be sufficient to stop the timer so that it could simply be restarted in OnStart
:
Me.ServiceTimer.Change(Timeout.Infinite, Timeout.Infinite)
If your task is started from it's own thread, you can ensure that it will be finished properly.
When it's instead running in the main-thread and...
... when the Windows Service Control Manager (SCM) calls the
OnStart()
,OnStop()
,OnPause()
, orOnContinue()
method, you only have ~60 sec before you must return. If you do not return within this time, then the SCM will mark that service as not responding. After a while, it can out right kill the process you are running in. If you need more time to process things during these methods, you can call the RequestAdditionalTime() method and tell the SCM that things are talking a bit longer that it expects. (See the OnStop() method in the example above.)
Read more: http://www.codeproject.com/KB/system/LexnnWinService.aspx
Upvotes: 3