当一个人应该使用Environment.Exit终止控制台应用程序?控制台、应用程序、个人、Exit

由网友(往事通缉犯)分享简介:我保持了一些在工作中有一件事我已经注意到了一些人的控制台应用程序是,他们称之为Environment.Exit(0)。I'm maintaining a number of console applications at work and one thing I've been noticing in a numbe...

我保持了一些在工作中有一件事我已经注意到了一些人的控制台应用程序是,他们称之为Environment.Exit(0)。

I'm maintaining a number of console applications at work and one thing I've been noticing in a number of them is that they call Environment.Exit(0).

一个示例程序是这样的:

A sample program would look like this:

public class Program
{
    public static void Main(string[] args)
    {
        DoStuff();
        Environment.Exit(0);
    }
}

我不明白什么是原来的程序员的意图是这样做呢?在我看来,即使没有Environment.Exit声明程序应该退出就好了。尽管如此,对于这些程序之一,它的控制台窗口已剩下的就应该即使在已经关闭的,所以我真的不知道发生了什么事有....

I don't understand what the intent of the original programmer was in doing this? In my mind even without the Environment.Exit statement the program should exit just fine. That said, for one of these programs, it's console window has been remaining even after it was supposed to have closed so I'm really not sure what's going on there....

我失去了一些东西呢?或者是有一个原因Environment.Exit应该叫在这种情况下?

Am I missing something here? Or is there a reason why Environment.Exit should be called in this instance?

推荐答案

有关要求的唯一理由退出()为主要手段的最后一行是,如果有可能可以运行其他前台线程。他们将保持运行,如果执行塌了下来的结束。即使在这种情况下,它通常会是一个更好的主意要么把一些明确的正常终止成其他线程 - 或使它们后台线程开始与

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.

如果你想从返回不同的退出code,更简单的方式来实现这一目标是宣布它返回 INT

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.

总之,我不认为你需要 Environment.Exit()在这里,这是值得一问你的同事正是为什么他们正在使用它 - 没准他们不能给你一个很好的理由,它的绒毛另一位则可以切出。

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.

阅读全文

相关推荐

最新文章