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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With