Search code examples
c#multithreadingabort

C# Threads.Abort()


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


Solution

  • Thread.Abort is not guaranteed to stop the thread and you should avoid using it if possible.

    Calling this method usually terminates the thread.

    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.