Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill thread, really!

I need to terminate a frozen thread, I set IsBackground as true but it stays alive. Thread's properties:

ThreadState = AbortRequested

IsBackground = true

When I examine the frozen spot I find the line below:

resultDetect = Detect(input, ref output);

The spot is a 3rd party code (Method Detect). The thread only updates resultDetect as you see. I need to abort that thread and re-start a new one to continue. Otherwise, the application waits and does nothing -fresh resultDetect needed-

How can I kill the thread that doesn't die?

like image 207
Nime Cloud Avatar asked Jul 25 '11 12:07

Nime Cloud


People also ask

How do I force kill a thread?

We can then forcefully kill the new main thread by calling the terminate() function on the thread's parent process. This will stop the thread immediately.

Can a thread be killed?

A thread is automatically destroyed when the run() method has completed. But it might be required to kill/stop a thread before it has completed its life cycle. Previously, methods suspend(), resume() and stop() were used to manage the execution of threads.

Is it possible to kill a thread in Java?

Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java. This method stops the execution of a running thread and removes it from the waiting threads pool and garbage collected. A thread will also move to the dead state automatically when it reaches the end of its method.


2 Answers

There's only one way to safely kill a hung thread in your application: Environment.Exit And even that can fail if the thread is running kernel code.

It's best not to use third-party code that hangs. If you have no choice, then run it in a separate process.

like image 193
Ben Voigt Avatar answered Oct 11 '22 09:10

Ben Voigt


If Detect transitions into unmanaged code then the CLR will defer the injection of the ThreadAbortException until it returns. This behavior changed in .NET 2.0 to make thread aborts a lot safer. The CLR is trying really hard to protect you from corrupting the state of the process which would be very likely in the case of unmanaged code since you do not get the benefit of the isolation of app domains which can be easily unloaded under an all managed scenario. Really, the only solution is to run this API in a separate process and use WCF, remoting, etc. to communicate with it.

like image 38
Brian Gideon Avatar answered Oct 11 '22 08:10

Brian Gideon