Take the 2-minute tour ×

Strange issue. I kill the main thread, but when the program ends, it still processes the code after this.Close().

Any ideas on how to stop that?

MessageBox.Show("Servers overloaded. Exiting.");
//...other code that processes even after it closes...
share|improve this question
How do you kill the main thread? Thread.Abort()? –  Mark Byers Feb 21 '10 at 19:57
WPF? Winforms? Asp.net? –  Oded Feb 21 '10 at 19:57
Its a desktop app. Im using this.Close() to kill the main thread. I only have a single thread running. –  James Jeffery Feb 21 '10 at 19:58
He's probably using WinForms. –  SLaks Feb 21 '10 at 19:58
add comment

3 Answers

Closing the window does not stop the thread.

You can use Environment.Exit to shutdown immediately.

share|improve this answer
No, you shouldn't. You should call Close and return to perform a graceful exit. –  SLaks Feb 21 '10 at 20:00
You shouldn't, but the OP asked how to kill the main thread. Close and return does not do that. (Nor does Abort actually.) As far as I know, the only (managed) way to immediately kill the main thread is to immediately kill the process. –  Josh Feb 21 '10 at 20:14
I didn't say this was a good idea - but that would be the proper way to actually KILL it. –  Reed Copsey Feb 21 '10 at 20:18
add comment

Unlike ASP.Net's Response.End(), calling Close will not abort the thread.

You need to add return; after calling Close() to exit the method.

share|improve this answer
But that begs the question, why is there any code after the Close() method if you don't want to execute it? Putting a return after Close() will just end up causing compiler warnings about unreachable code. –  Josh Feb 21 '10 at 20:16
This won't prevent code outside the form from running, though - I agree this is a better approach, but it doesn't answer the question... –  Reed Copsey Feb 21 '10 at 20:21
add comment

Why would it stop at Close()? It is still going to exit your method - most things like Close() are going to involve sending something to the windows message queue and having it processed. If you need to exit NOW, then perhaps Environment.FailFast...

share|improve this answer
add comment

Your Answer


