If a thread is running a function func1
that calls another function func2
inside it...
Then I called thread.Abort()
Will this stop func1
only
OR func1
and func2
and all the functions func1
has called??
Thanks
Edit: Here are more detail:
func1
is called in a new thread, it continuously calls func2
on regular basis...
func2
begin doing some work only if some array is not null.. it finishes it and return
When supervisor wants to save data, it aborts Thread of func1
- and then makes array null, saves data, then fill in the array with new one.. and starts Thread with func1
again..
Sometimes exception is raised because array is null in func2
.. so func1 abort did not affect func2
For who cares:
After more debugging I found that the thread is initialized once more before start; causing a thread to run in background...
This unreferenced one in background is not affected with Abort()... so it will continue working and it tries to use null array...
At the end:
Abort() will end your thread, except in some conditions (mentioned above in other's answer)
Abort() will not end a thread after being unreferenced (obviously)
Thanks!!
Thread.Abort
is not guaranteed to stop the thread and you should avoid using it if possible.Emphasis mine.
What it does is raise a
ThreadAbortException
in the target thread. If you catch this exception, the code will continue executing until it reaches the end of the catch block, at which point the exception is automatically rethrown. If you don't catch it, it is similar to a normal exception - it propagates up the call stack.Assuming you don't catch the exception, all the code running in that thread will stop running. Other threads that were started from that thread will not be affected.
Anything started within that thread will be aborted.
You could be facing a race condition, where your main routine nulls the array before the ThreadAbortException reaches the func1 thread but after func2 checks for null array.
As a minimum, your main code and func2 should use a lock around the array. You should also test that the func1 thread is dead before restarting it again. And as everyone else has said, signal a thread to stop rather than relying on Thread.Abort.
I'm not 100% sure from your description that func2 is called from within the func1 thread, but if func2 is run on a different thread that's started from within func1, killing the func1 thread won't affect func2 as all threads exist as children of your parent process, not of the thread that they were started from.