Stopping Windows Service with Thread

T

tshad

I have a Service that starts a thread that never ends.

When I stop the service from the Service Applet, does it kill the thread or
do I need to do it myself?

If it isn't killed, what happens when I start the service again.

**************************************************
Protected Overrides Sub OnStart(ByVal args() As String)
Dim theThread As Thread
theThread = New Thread(AddressOf StartThreads)
theThread.Start()
End Sub

Protected Overrides Sub OnStop()
End Sub

Private Sub StartThreads()
Dim oCredit1 As New CreditProcessor

....
End Sub
******************************************************

Thanks,

Tom
 
S

Stephany Young

There is a gotcha with the IsBackground property of a Thread object is that
when the process is terminated, the thread in question is killed dead. It
does not get the opportunity to execute any 'clean-up' logic and can be
compared to killing a process from Task Manager.

For critical threads in services I use something like this:

Private m_thread As Thread = Nothing
Private m_threadstop As Boolean = False

Protected Overrides Sub OnStart(ByVal args() As String)

m_thread = New Thread(AddressOf StartThreads)

m_thread.Start()

End Sub

Protected Overrides Sub OnStop()

m_stopthread = True

m_thread.Join()

End Sub

Private Sub StartThreads()

' Any required start-up logic goes here

While Not m_threadStopped

' the main logic the thread goes here

If WeNeedToExitEarly() Then Exit While

Thread.Sleep(1)
End While

' Any required tidy-up logic goes here

End Sub

The each iteration of the control loop in thread needs to be short enough
(time wise) so that the service can respond to the Stop request from the
Service Control Manager in a timely fashion i.e. within about 20 seconds.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top