Thead Completion

  • Thread starter Thread starter TCORDON
  • Start date Start date
T

TCORDON

How can I determine the moment a thread finishes?

I start the thread this way:

Dim x As New Threading.Thread(AddressOf (MySub))

x.Start



Is there any x.Finished type of Event or how can do this?

Thanks
 
There is no built-in event.

You can have MySub raise a custom event or you can use a custom thread
class that adds this event. The only kink here is that Thread is
declared as NotInheritable so you have to proxy all of the
properties/methods from your custom class to the base Thread instance
and the containing variable must be declared as your custom type and
not Thread. Would have been much simpler if Thread was not declared
NotInheritable and if Start was overridable.

HTH,

Sam


Incomplete example (only proxies the Start method):


Imports System.Threading

Public Class ConsiderateThread
Private _underlyingThread As Thread
Private _underlyingStart As ThreadStart

Public Event ThreadCompleted As EventHandler

Public Sub New(ByVal start As ThreadStart)
_underlyingStart = start
_underlyingThread = New Thread(AddressOf ConsiderateStart)
End Sub

Public Sub Start()
_underlyingThread.Start()
End Sub

Private Sub ConsiderateStart()
_underlyingStart.Invoke()
RaiseEvent ThreadCompleted(Me, EventArgs.Empty)
End Sub
End Class

Public Class ConsiderateThreadTester
Public Shared Sub Test()
Dim t As New ConsiderateThread(AddressOf DoSomething)
AddHandler t.ThreadCompleted, AddressOf DoSomethingDone
t.Start()
Thread.Sleep(5000)
Console.WriteLine("Test Done")
End Sub
Public Shared Sub DoSomethingDone(ByVal sender As Object, ByVal e
As EventArgs)
Console.WriteLine("DoSomethingDone")
End Sub
Public Shared Sub DoSomething()
Console.WriteLine("DoSomething")
End Sub
End Class
 
Back
Top