How to kill thread?

B

Brett

I'm trying to kill a thread spawned this way:
Form1 spawns Class1 via Thread.start()

Here's my code to kill the thread:

If (t.ThreadState.ToString = "SuspendedRequested, WaitSleepJoin") Or
(t.ThreadState.ToString = "Suspended") Or (t.ThreadState.ToString =
"WaitSleepJoin, Suspended") Then
Else
t.Abort()
End If

The above runs when I close the application. The abort is hit and the main
form closes. Looking at the threads window, I can see the class spawned by
the thread is still active. It's suspend status is 1. It is also using
100% cpu. How can I debug why this thread will not die?


Thanks,
Brett
 
R

Ray Cassick

If you want the background thread to die when the parent app closes just set
the threads background property to true before you start it.
 
B

Brett

No where in that post do I set the background property. If I try to do
this:
t.ThreadState.Background = True

I get this:
Constant cannot be the target of an assignment.

In summary, no - the the thread doesn't help.

Brett
 
B

Brett

Actually, I have the correct syntax and that seems to be working:
t.IsBackground = True

When the app is closing, I'm doing this:
If (t.ThreadState.ToString = "SuspendedRequested, WaitSleepJoin") Or
(t.ThreadState.ToString = "Suspended") Or (t.ThreadState.ToString =
"WaitSleepJoin, Suspended") Then
Else
t.Abort()
End If

That probably isn't needed anymore. The second thread is closing without
it, now that the background is set to true.

Thanks,
Brett
 
R

Ray Cassick

Right, this will cause (the runtime I think) to kill the thread off when the
parent process dies.

The only thing you need to be careful of is what you are doing in that
thread. I am fairly certain that you have no control over what is being done
in that thread when it gets killed. If you are looping through a list for
instance your thread might die before the current loop is done.
 
B

Brett

It may not finish the entire loop but will finish the interaction it's in
correct?

Brett
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top