views:

62

answers:

1

Hi, I have heard that on .NET CF Environment.Exit does not work. Is there any universal way how to terminate (in a standard way) the console app? Thank you

+1  A: 

An application automatically terminates when there is no non-background thread running.

A thread automatically stops running when there is no more code to execute.

So, just make your application have no more code to execute when you want it to terminate.

class Program
{
    static void Main()
    {
        ConsoleKeyInfo cki;

        do
        {
            Console.Write("Press a key: ");
            cki = Console.ReadKey(true);
            Console.WriteLine();

            if (cki.Key == ConsoleKey.D1)
            {
                Console.Write("You pressed: 1");
            }
        }
        while (cki.Key != ConsoleKey.D2);

    } // <-- application terminates here
}
dtb
Yep but that is not explicit termination. The workaround is not difficult (enclose the code with bool) or whatever, but I would like to know the way (if there is) :)
Petr
@Petr: Letting the application end itself is much better than terminating it forcefully. I'm not sure why you'd ever use Environment.Exit.
dtb
@dtb: What about main menu? Press 1 for start, 2 to exit
Petr
@Petr: Just make your application come to a normal end when the user pressed '2'. No need for Environment.Exit.
dtb