Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Thread Termination and Thread.Abort()

In MSDN, the description of the Thread.Abort() method says: "Calling this method usually terminates the thread."

Why not ALWAYS?

In which cases it doesn't terminate the thread?

Are there any other possibility to terminate threads?

like image 438
user101375 Avatar asked Feb 12 '10 13:02

user101375


2 Answers

Thread.Abort() injects a ThreadAbortException on the thread. The thread may cancel the request by calling Thread.ResetAbort(). Also, there are certain code parts, such as finally block that will execute before the exception is handled. If for some reason the thread is stuck in such a block the exception will never be raised on the thread.

As the caller has very little control over the state of the thread when calling Abort(), it is generally not advisable to do so. Pass a message to the thread requesting termination instead.

like image 122
Brian Rasmussen Avatar answered Oct 08 '22 19:10

Brian Rasmussen


In which cases it doesn't terminate the thread?

This question is a duplicate.

What's wrong with using Thread.Abort()

Are there any other posibility to terminate threads?

Yes. Your problem is that you should never start up a thread that you cannot tell politely to stop, and it stops in a timely manner. If you are in a situation where you have to start up a thread that might be (1) hard to stop, (2) buggy, or worst of all (3) hostile to the user, then the right thing to do is to make a new process, start the thread in the new process, and then terminate the process when you want the thread to go down. The only thing that can guarantee safe termination of an uncooperative thread is the operating system taking down its entire process.

See my excessively long answer to this question for more details:

Using lock statement within a loop in C#

The relevant bit is the bit at the end where I discuss what the considerations are regarding how long you should wait for a thread to kill itself before you abort it.

like image 45
Eric Lippert Avatar answered Oct 08 '22 19:10

Eric Lippert