Question

I know Exitthread can only be called from within the Thread, and Abort can be used at anytime anywhere as long as you can access the Thread object. But are there other significant differences between these two methods (operation-wise) when you need to force-close a Thread?

Was it helpful?

Solution

Yes absolutely.

Thread.Abort() causes horrible, difficult-to-find bugs and ExitThread() doesn't.

Calling Thread.Abort() causes an exception to be thrown inside the thread, and that can cause all kinds of grief.

Also, of course, ExitThread() only works with threads that are running message loops.

Also note that code after the call to ExitThread() will still be executed, although UI calls such as MessageBox.Show() won't do anything:

private void button1_Click(object sender, EventArgs e)
{
    Application.ExitThread();
    MessageBox.Show("This won't be shown because the UI is being shut down.");
    Debug.WriteLine("But this is still executed");
}

If you want to exit threads in a controlled manner, you need to actively support it by writing code to do so.

Here's a good Microsoft article about it: http://msdn.microsoft.com/en-us/library/dd997364.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top