如何正确退出 C# 应用程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12977924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:11:24  来源:igfitidea点击:

How to properly exit a C# application?

c#winformsexit

提问by John Ernest Guadalupe

I have a published application in C#. The problem here is whenever I close the main form by clicking on the red exit button, it closes the form but it doesn't close the application. I found this out when I tried shutting down the computer, hopeful that the application I made was running smoothly then I was bombarded by a lot of child windows with which I have put MessageBoxAlerts.

我在 C# 中有一个已发布的应用程序。这里的问题是每当我通过单击红色退出按钮关闭主窗体时,它会关闭窗体但不会关闭应用程序。当我尝试关闭计算机时,我发现了这一点,希望我制作的应用程序运行顺利,然后我被许多放置MessageBox警报的子窗口轰炸。

I tried Application.Exitbut it still calls all the child windows and alerts and I don't know how to use Environment.Exitand which integer to put into it.

我试过了,Application.Exit但它仍然调用所有子窗口和警报,我不知道如何使用Environment.Exit以及将哪个整数放入其中。

By the way, whenever my forms call the formclosedor form closingevent I close the application with a this.Hide()function; Does that affect how my application is behaving now?

顺便说一下,每当我的表单调用formclosedorform closing事件时,我都会用一个this.Hide()函数关闭应用程序;这会影响我的应用程序现在的行为方式吗?

采纳答案by Furqan Safdar

From MSDN:

来自 MSDN:

Application.Exit

申请.退出

Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This is the code to use if you are have called Application.Run (WinForms applications), this method stops all running message loops on all threads and closes all windows of the application.

通知所有消息泵它们必须终止,然后在消息处理完毕后关闭所有应用程序窗口。如果您已调用 Application.Run(WinForms 应用程序),则这是要使用的代码,此方法会停止所有线程上的所有正在运行的消息循环并关闭应用程序的所有窗口。

Environment.Exit

环境.退出

Terminates this process and gives the underlying operating system the specified exit code. This is the code to call when you are using console application.

终止此进程并为底层操作系统提供指定的退出代码。这是使用控制台应用程序时要调用的代码。

This article, Application.Exit vs. Environment.Exit, points towards a good tip:

这篇文章Application.Exit vs. Environment.Exit指出了一个很好的提示:

You can determine if System.Windows.Forms.Application.Runhas been called by checking the System.Windows.Forms.Application.MessageLoopproperty. If true, then Run has been called and you can assume that a WinForms application is executing as follows.

您可以System.Windows.Forms.Application.Run通过检查System.Windows.Forms.Application.MessageLoop属性来确定是否已被调用。如果为 true,则 Run 已被调用,您可以假设 WinForms 应用程序按如下方式执行。

if (System.Windows.Forms.Application.MessageLoop) 
{
    // WinForms app
    System.Windows.Forms.Application.Exit();
}
else
{
    // Console app
    System.Environment.Exit(1);
}

Reference: Why would Application.Exit fail to work?

参考:为什么 Application.Exit 无法工作?

回答by LightStriker

Do you do:

你做:

Application.Run(myForm);

in your Main()?

在你的 Main() 中?

I found it a very easy way to kill the application when the form is closed.

我发现这是一种在表单关闭时终止应用程序的非常简单的方法。

回答by Servy

By the way. whenever my forms call the formclosed or form closing event I close the applciation with a this.Hide() function. Does that affect how my application is behaving now?

顺便一提。每当我的表单调用 formclosed 或 form closed 事件时,我都会使用 this.Hide() 函数关闭应用程序。这会影响我的应用程序现在的行为方式吗?

In short, yes. The entire application will end when the main form (the form started via Application.Runin the Mainmethod) is closed (not hidden).

简而言之,是的。当主形式(通过启动的形式整个应用程序将结束Application.RunMain方法)被关闭(不隐藏)。

If your entire application should always fully terminate whenever your main form is closed then you should just remove that form closed handler. By not canceling that event and just letting them form close when the user closes it you will get your desired behavior. As for all of the other forms, if you don't intend to show that same instance of the form again you just just let them close, rather than preventing closure and hiding them. If you are showing them again, then hiding them may be fine.

如果您的整个应用程序在主表单关闭时始终完全终止,那么您应该删除该表单关闭处理程序。通过不取消该事件并在用户关闭它时让它们关闭,您将获得所需的行为。至于所有其他表单,如果您不打算再次显示该表单的同一个实例,您只需让它们关闭,而不是阻止关闭和隐藏它们。如果您再次显示它们,则隐藏它们可能没问题。

If you want to be able to have the user click the "x" for your main form, but have another form stay open and, in effect, become the "new" main form, then it's a bit more complicated. In such a case you will need to just hide your main form rather than closing it, but you'll need to add in some sort of mechanism that will actuallyclose the main form when you really do want your app to end. If this is the situation that you're in then you'll need to add more details to your question describing what types of applications should and should not actually end the program.

如果您希望能够让用户单击主表单的“x”,但让另一个表单保持打开状态,并且实际上成为“新”主表单,那么它就有点复杂了。在这种情况下,您只需要隐藏主窗体而不是关闭它,但是您需要添加某种机制,当您确实希望应用程序结束时,它实际上会关闭主窗体。如果您处于这种情况,那么您需要在问题中添加更多详细信息,说明哪些类型的应用程序应该和不应该实际结束程序。

回答by Scott Chamberlain

I know this is not the problem you had, however another reason this could happen is you have a non background thread open in your application.

我知道这不是您遇到的问题,但是可能发生的另一个原因是您在应用程序中打开了一个非后台线程。

using System;
using System.Threading;
using System.Windows.Forms;

namespace Sandbox_Form
{
    static class Program
    {
        private static Thread thread;

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            thread = new Thread(BusyWorkThread);
            thread.IsBackground = false;
            thread.Start();

            Application.Run(new Form());

        }

        public static void BusyWorkThread()
        {
            while (true)
            {
                Thread.Sleep(1000);
            }
        }
    }
}

When IsBackgroundis falseit will keep your program open till the thread completes, if you set IsBackgroundto truethe thread will not keep the program open. Things like BackgroundWoker, ThreadPool, and Taskall internally use a thread with IsBackgroundset to true.

IsBackgroundfalse它会保持你的程序中打开,直到线程完成,如果你设置IsBackgroundtrue线程将不会保持程序中打开。诸如BackgroundWokerThreadPool和之类的东西Task都在内部使用一个IsBackground设置为的线程true

回答by Omar Moodie

All you need is System.Environment.Exit(1);

所有你需要的是 System.Environment.Exit(1);

And it uses the system namespace "using System" that's pretty much always there when you start a project.

它使用系统命名空间“using System”,当你开始一个项目时,它几乎总是存在。

回答by joe pelletier

Environment.Exit(exitCode); //exit code 0 is a proper exit and 1 is an error

回答by Techcraft7

I would either one of the following:

我会选择以下任一项:

Application.Exit();

Application.Exit();

for a winform or

对于 winform 或

Environment.Exit(0);

环境.退出(0);

for a console application (works on winforms too).

对于控制台应用程序(也适用于 winforms)。

Thanks!

谢谢!

回答by Anton Tsches

In this case, the most proper way to exit the application in to override onExit() method in App.xaml.cs:

在这种情况下,最合适的退出应用程序的方法是覆盖 App.xaml.cs 中的 onExit() 方法:

protected override void OnExit(ExitEventArgs e) {
    base.OnExit(e); 
}