When should one use Environment.Exit to terminate a console application?

The only reason for calling Exit() as the last line of the Main method is if there might be other foreground threads running. They would stay running if execution just fell off the end of Main. Even in this case, it would usually be a better idea either to put in some explicit graceful termination into the other threads – or make them background threads to start with.

If you ever want to return a different exit code from Main, the simpler way to achieve that is to declare it to return int.

In short, I don’t think you need Environment.Exit() here, and it’s worth asking your colleagues exactly why they’re using it – chances are they won’t be able to give you a good reason, and it’s another bit of fluff you can cut out.

Leave a Comment