This is the first time I have tried to use multiple threads in an
application so I hope someone can help me.
I am using a second thread to do some work but I need to be able to cancel
the thread at any time. I have implemented the thread as below.
The problem I have is that usually when I call the CancelThread routine
while the thread is running the application hangs.
I tried putting a break point at WUThreadisFinished.Set().
Normally (without calling the CancelThread) the break point is reached. But
usually when I call the CancelThread the break point is never reached.
How can this be. I thought if the code is in the 'finally' part of a try
statement then that code cannot be bypassed.
The hang occurs at WUThreadisFinished.WaitOne() line and it seems the thread
somehow stops without doing WUThreadisFinished.Set().
What am I doing wrong?
Thanks
Fred
Private CancelWUThread As New System.Threading.ManualResetEvent(False)
Private WUThreadisFinished As New System.Threading.ManualResetEvent(True)
Private Sub StartThread()
Dim th As New System.Threading.Thread(AddressOf DoSomeWork)
CancelWUThread.Reset()
WUThreadisFinished.Reset()
th.Start()
End Sub
Private Sub CancelThread()
If CancelWUThread.Set() Then
WUThreadisFinished.WaitOne()
End If
End Sub
Private Sub DoSomeWork()
Try
'
'Doing some work here
'
Do
'
'Do some more work here
'
Loop Until CancelWUThread.WaitOne(0, False) Or ...
Finally
WUThreadisFinished.Set()
End Try
End Sub