I\'m maintaining a number of console applications at work and one thing I\'ve been noticing in a number of them is that they call Environment.Exit(0).
A sample progr
In SSIS when you have an Execute Process Task and you want to know if process is failure , this method is useful.
This is [compatibility] for command-line programs to indicate success or failure to an underlying shell, and is inherited from older C-style main loops where the prototype of the main function was
int main(void);
int main(int argc, char *argv[]);
The return value of 0 traditionally meant success, while non-zero meant failure or something else, depending on what the programmer decided.
Reference:
wiki for more information on the main
function.
MSDN documenttion on Environment.Exit()
Environment.Exit() : Terminates this process and gives the underlying operating system the specified exit code.
This is really used when other applications are waiting on the result of your console app. For example, SSRS (tool) can launch a console app, and waits to get back a success of failure response. The Environment.Exit(0) sends back a successful execution message.
In .net core, as of right now, one must use Environment.Exit
to terminate their program on Mac. Purely returning from main
doesn't stop the process and it keeps running until the user aborts it. Patterns like:
public class Program
{
public static void Main(string[] args)
{
Environment.Exit(TryRun(args));
}
}
are common in my work place because we want to ship for both Windows and Mac.
I'm currently using Environment.Exit()
in a console app where I don't want to throw ugly exception text back to the console. Instead I just notice the condition, write a user friendly message to the screen about what happened and then call Environment.Exit()
.
Otherwise, you shouldn't need to call it from Main()
in a basic 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.