I created a Windows service in VB.NET. The OnStart creates a worker thread and returns. The worker thread starts up ok and attempts to connect to a db. If the connection is made, the thread goes into an infinite loop, which is the expected behavior.
Dim _shutdown As Boolean = False
Private _oPollingThread As Thread
Protected Overrides Sub OnStart(ByVal args() As String)
_oPollingThread = New Thread(New System.Threading.ThreadStart(AddressOf PollProcess))
_oPollingThread.Start()
End Sub
If the service is shut down manually (by a Windows user going into Services and clicking Stop), the OnStop sets a boolean; the worker thread sees this and shuts itself down successfully, the OnStop joins, and the service stops. All good.
Protected Overrides Sub OnStop()
_shutdown = True
' Allow poll process to shut down gracefully (give it up to ten seconds...)
Dim shutdownCount As Integer = 0
Do While _oPollingThread.Join(1000) = False And shutdownCount < 10
shutdownCount = shutdownCount + 1
Loop
If _oPollingThread.IsAlive = True Then
_oPollingThread.Abort()
End If
End Sub
The problem is, how do I get the service to stop if the worker thread does not connect to the db? Once the worker thread terminates (instead of going into its infinite loop), the Windows service stays active and OnStop does not run.