grantdaddy
asked on
Properly stopping a .net windows service
How can I stop a vb.net windows service from within the code and have the service show as stopped in the WMI? For example, if I am looking for a config file on startup and don't find it, I just want to stop the service. I tried the code below, and it does stop executing the code in the DoWork routine (because the event log doesn't get wriitten to anymore), but the service still shows as started in the WMI.
Public Class TestService
Private _worker As New Worker()
Protected Overrides Sub OnStart(ByVal args() As String)
Dim wt As System.Threading.Thread
Dim ts As System.Threading.ThreadStart
ts = AddressOf _worker.DoWork
wt = New System.Threading.Thread(ts)
wt.Start()
End Sub
Protected Overrides Sub OnStop()
_worker.StopWork()
End Sub
Public Class Worker
Private m_thMain As System.Threading.Thread
Private m_booMustStop As Boolean = False
Private m_rndGen As New Random(Now.Millisecond)
Public Sub StopWork()
m_booMustStop = True
If Not m_thMain Is Nothing Then
If Not m_thMain.Join(100) Then
m_thMain.Abort()
End If
End If
End Sub
Public Sub DoWork()
Dim TestCounter As Integer = 0 'we'll stop the the service after we loop through twice
m_thMain = System.Threading.Thread.CurrentThread
Dim i As Integer = m_rndGen.Next
m_thMain.Name = "Thread" & i.ToString
While Not m_booMustStop
TestCounter += 1
System.Diagnostics.EventLog.WriteEntry("EmptyService", "Start work: " & m_thMain.Name)
System.Threading.Thread.Sleep(10000)
System.Diagnostics.EventLog.WriteEntry("EmptyService", "Finish work: " & m_thMain.Name)
If TestCounter > 1 Then StopWork()
End While
End Sub
End Class
End Class
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
1) Check the value of service.CanStop
This should be true else the service is created such that it can't be stopped.
2) Add this line after service.Stop()
service.Refresh()
3) Then check the status property value:
service.Status()
This should be true else the service is created such that it can't be stopped.
2) Add this line after service.Stop()
service.Refresh()
3) Then check the status property value:
service.Status()
ASKER
Is the code below what you would typically use?
Open in new window