Thread problem

  • Thread starter Thread starter Cor
  • Start date Start date
C

Cor

Hi Fred,

I do not see an instruction mythread.abort which is to cancel a thread in
your code.

Cor
 
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
 
When I cancel the thread I want to immediately restart it hence I send a
Cancel signal (CancelWUThread.Set()) to the thread then wait for it to
finish by waiting for the thread to execute WUThreadisFinished.Set().
The trouble with the abort method is that you don't know when the thread is
actually finished so how do you know when it is safe to restart the thread.

Thanks
Fred
 
Back
Top