Correct Way to Exit From Console Application [duplicate]

好久不见. 提交于 2019-12-07 08:04:10

问题


I've done some reading here, and here and I'm still confused about if I should use Enviorment.Exit() in my console application.

In a method, I have the following code if the user types exit at the prompt,

if(userSelect == "exit"){
{
    Environment.Exit(0);
}

Update:

class Program
    {
        public static void Main(string[] args)
        {

            Console.WriteLine("Welcome to my Console App");
            Console.WriteLine();
            consoleManager();

        }


        public static void consoleManager()
        {
            string consolePrompt="ConsoleApp">";


            string whichMethod="";
            Console.Write(consolePrompt);
            whichMethod = Console.ReadLine();

            if(whichMethod == "view enties")
            {           
                viewEntry();
            }
            else
                if(whichMethod == "Add Entry")
                {
                    addEntry();
                }
                else
                    if(whichMethod == "exit"){
                    {
                        //what to do here
                    }
                }
            else{
                help();
            }
        }

回答1:


Go through the MSDN Documentation for - Environment.Exit, it explains the paramter

the exitCode parameter, use a non-zero number to indicate an error. In your application, you can define your own error codes in an enumeration, and return the appropriate error code based on the scenario. For example, return a value of 1 to indicate that the required file is not present, and a value of 2 to indicate that the file is in the wrong format.

So if you say Exit(0), you will say your process exited successfully without any error. If you use any System Error Code, you are notifying the operating system what when wrong. In your case Environment.Exit(0) is sufficient.

Edit I am pretty sure, you are overthinking it. Points to consider -

  1. If you are exiting from Main a simple return statement would be sufficient.
  2. Elsewhere use Enviorment.Exit(), because return statement will return you to the Main method and program will still continue to run.
  3. I hope you are familiar with void Main(string[] args) and int Main(string[] args). The difference is the return value. You use it incase you want to return a error code, 0 for success and other numbers for various errors. You can very well use the System Error Code linked above.
  4. It boils down to the point - if the caller of your console program uses the return value or not. If its a dos prompt where you are running it will be ignored. If some external application is running your console it may process your output.


来源:https://stackoverflow.com/questions/35393877/correct-way-to-exit-from-console-application

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