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
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