简体   繁体   中英

WinForms Application.Exit does not exit the app necessarily

on the MSDN I have read that calling Application.Exit does not have to exit every time. I would like to know what could cause that? I mean when I could expect that Application.Exit will not exit the application?

Application.Exit will call FormClosing for every opened form, and this event can be cancelled. If any form has cancelled this event, Application.Exit will stop without doing anything. Else all forms will be closed. But, if you have any non-background threads working (in additional to main thread) your application will not be finished by Application.Exit.

Take the typical setup, the default generated by VS for a WinForms project.

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new YourForm());
}

Now in your form if an error occurs in the constructor,

public YourForm()
{
    InitializeComponent();

    try
    {
       //do some stuff + error occurs...

       //simulate error
       throw new exception("blah");

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());                 
        Application.Exit(); //useless 
    }
}

It is easy to think this would kill / exit the app, however YourForm would in fact appear and the application would still be running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM