在c#中退出控制台应用程序的命令是什么?
当前回答
当main函数完成运行时,控制台应用程序将退出。“回归”将实现这一点。
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("I'm running!");
return; //This will exit the console application's running thread
}
}
如果你要返回一个错误代码,你可以这样做,它可以从初始线程外部的函数访问:
System.Environment.Exit(-1);
其他回答
当main函数完成运行时,控制台应用程序将退出。“回归”将实现这一点。
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("I'm running!");
return; //This will exit the console application's running thread
}
}
如果你要返回一个错误代码,你可以这样做,它可以从初始线程外部的函数访问:
System.Environment.Exit(-1);
你可以使用Environment.Exit(0);和应用程序。退出
Environment.Exit(0)更干净。
有几种选择,按最合适的顺序排列:
从程序返回一个整型。主要方法 抛出异常,但不在任何地方处理它(用于意外错误情况) 为了强制在其他地方终止,System.Environment.Exit(不可移植!见下文)
编辑2013年9月以提高可读性
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.
您可以使用Environment.Exit(0)和Application.Exit。
exit():终止此进程并为底层操作系统提供指定的退出码。