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

送分小仙女□ 提交于 2019-11-27 13:53:22

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.

Anand Shah

Basically the statement Environment.Exit(0) tells the Operating system that this is a "clean" exit. There are other numbers as well each with a different meaning like Environment.Exit(1)

However one thing to note is that the "Main" has been declared as returning nothing "void", so the exit code will really not have a meaning to it.

Just in case you wanted to know more about the different exit codes have a look here

system Error Codes

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 SSIS when you have an Execute Process Task and you want to know if process is failure , this method is useful.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!