Threads and scope

C

Chris Dunaway

I use the class below as a base class to make object that execute in
their own thread. If I create a derived class and instantiate an
instance of that class, what happens to the thread if the instance goes
out of scope? Will the thread continue to run? Does the thread run
independently of the object? Does the thread keep the object alive
even though my reference to it goes out of scope?

Public MustInherit Class ThreadWrapper

'Our thread object
Public ReadOnly Thread As System.Threading.Thread

Public Sub New()
'Create the thread
Me.Thread = New System.Threading.Thread(AddressOf
Me.StartThread)
End Sub

'Starts execution of the thread
Public Overridable Sub Start()
Me.Thread.Start()
End Sub

'Aborts the thread. this sub can be overridden to kill the thread
more gracefully
Public Overridable Sub [Stop]()
Me.Thread.Abort()
End Sub

'Property to indicate the thread is completed
Private m_IsCompleted As Boolean
Public ReadOnly Property IsCompleted() As Boolean
Get
Return m_IsCompleted
End Get
End Property

'When the thread is started, this is the sub that is called, it in
turn calls the Execute method which
'derived classes must override.
Private Sub StartThread()
m_IsCompleted = False
Execute()
m_IsCompleted = True
End Sub

'This is the sub that performs the "work" of the thread. It must
be overridden in the derived class
Protected MustOverride Sub Execute()

End Class
 
M

Mattias Sjögren

If I create a derived class and instantiate an
instance of that class, what happens to the thread if the instance goes
out of scope? Will the thread continue to run?

Yes, the thread terminates when the method you instantiated it with
(StartThread) exits.

Does the thread run independently of the object?
Yes


Does the thread keep the object alive
even though my reference to it goes out of scope?

I don't think the thread itself necessarily keeps the object alive,
but the code that the thread runs will certainly keep it alive as long
as it's needed.



Mattias
 

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

Similar Threads


Top