What is the command in C# for exiting a console application?
-
2Does this answer your question? How do I specify the exit code of a console application in .NET?Michael Freidgeim– Michael Freidgeim2021-11-15 06:23:32 +00:00Commented Nov 15, 2021 at 6:23
-
The canonical is How do I specify the exit code of a console application in .NET?.Peter Mortensen– Peter Mortensen2022-01-17 22:42:15 +00:00Commented Jan 17, 2022 at 22:42
-
For exiting by Trace.Assert() (usually conditional) and its exit code (134 on some platforms), see this.Peter Mortensen– Peter Mortensen2022-01-18 23:21:54 +00:00Commented Jan 18, 2022 at 23:21
4 Answers
You can use Environment.Exit(0); and Application.Exit
Environment.Exit(0) is cleaner.
4 Comments
Environment.Exit requires that you have SecurityPermissionFlag.UnmanagedCode permissions - which might be troublesome for some.Several options, by order of most appropriate way:
- Return an int from the Program.Main method
- Throw an exception and don't handle it anywhere (use for unexpected error situations)
- To force termination elsewhere,
System.Environment.Exit(not portable! see below)
Edited 9/2013 to improve readability
Returning with a specific exit code: As Servy points out in the comments, you can declare Main with an int return type and return an error code that way. So there really is no need to use Environment.Exit unless you need to terminate with an exit code and can't possibly do it in the Main method. Most probably you can avoid that by throwing an exception, and returning an error code in Main if any unhandled exception propagates there. If the application is multi-threaded you'll probably need even more boilerplate to properly terminate with an exit code so you may be better off just calling Environment.Exit.
Another point against using Evironment.Exit - even when writing multi-threaded applications - is reusability. If you ever want to reuse your code in an environment that makes Environment.Exit irrelevant (such as a library that may be used in a web server), the code will not be portable. The best solution still is, in my opinion, to always use exceptions and/or return values that represent that the method reached some error/finish state. That way, you can always use the same code in any .NET environment, and in any type of application. If you are writing specifically an app that needs to return an exit code or to terminate in a way similar to what Environment.Exit does, you can then go ahead and wrap the thread at the highest level and handle the errors/exceptions as needed.
6 Comments
Console applications will exit when the main function has finished running. A "return" will achieve this.
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("I'm running!");
return; //This will exit the console application's running thread
}
}
If you're returning an error code you can do it this way, which is accessible from functions outside of the initial thread:
System.Environment.Exit(-1);