How to stop a running thread?
Hi,
I have a VB.NET main form (mdi child) which will display data from various source in a TabPage control.
I've wrote a class contain a series of calls, and is invoked by a delegate's BeginInvoke method in the main form.
I found that when user close a mdi main form, the thread will continue to run until it finish. I know that if I can put some control in the worker thread to stop running when the calling form is closed, I can solve the problem.
But My problem is that how can the worker thread know the main mdi form is closed? Even if I set a variable for this, seems the thread can't access it.
since the main form is a mdi form, more than one instance may open concurrently, my worker thread should be able to distinguish its calling form is closed.......any help?
Thx!!
Re: How to stop a running thread?
You have to stop it like this:
Code:
Private CancelThread As New System.Threading.ManualResetEvent(False)
Private ThreadIsCanceled As New System.Threading.ManualResetEvent(False)
sub CancelThread()
CancelThread.Set()
End sub
sub ThreadStart()
Dim th As New System.Threading.Thread(AddressOf ThreadRun()
CancelThread.Reset()
hreadIsCanceled.Reset()
th.Start()
End sub
Sub ThreadRun()
While Not CancelThread.WaitOne(0, False)
'whatever
End While
If CancelThread.WaitOne(0, False) Then
PB1.Visible = False
ThreadIsCanceled.Set()
End If
'end of thread
CancelThread.Set()
End sub
Succes!!
Re: How to stop a running thread?
Hi,
Thx for your reply, but I don't quite understand what the code is doing, can you elaborate more?
thx~
Re: How to stop a running thread?
Oh I c, that means I can use BeginInvoke?