4

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?

Jordy
  • 1,796
  • 14
  • 29

1 Answers1

6

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

Matthew Watson
  • 90,570
  • 7
  • 128
  • 228
  • So if you have the luxury to choose between the two, always choose ExitThread? – Jordy Jun 04 '13 at 08:35
  • Yes, but only for threads that are running a message pump (e.g. the main thread in a Windows Forms app). For background tasks, you should use cooperative cancellation as discussed in the Microsoft article I linked. Getting thread cancellation right is often more complicated than you might think at first. – Matthew Watson Jun 04 '13 at 08:37