20

I am using VSTS 2008 + .Net 3.5 + C# to develop Windows Forms application. My confusion is, seems Application.Exit does not force application to terminate? If not, which method should I call to make application terminate?

EDIT 1:

Normally the main method is like this, how to exit Main function gracefully without calling Environment.Exit?

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        try
        {
            Application.Run(new Form1());
        }
        catch (Exception ex)
        {
            Console.WriteLine (ex.Message);
        }
    }

thanks in advance, George

George2
  • 44,761
  • 110
  • 317
  • 455

6 Answers6

37

Application.Exit really just asks the message loop very gently.

If you want your app to exit, the best way is to gracefully make it out of Main, and cleanly close any additional non-background threads.

If you want to be brutal... Environment.Exit or Environment.FailFast? note this is harsh - about the same as killing your own Process.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Thanks Marc, I am confused how to exit Main function gracefully. I have posted my code in my original post under EDIT 1 section. Any ideas why? – George2 Jun 29 '09 at 08:38
  • Marc, I read your reply, but where to call Close? Inside Main or replace the code to call Application.Exit with code to call Close? – George2 Jun 29 '09 at 08:55
  • 1
    Either ;-p Presumably, though, you are in the form when you want to exit (perhaps as a button etc) - so the form can issue this.Close() to itself. – Marc Gravell Jun 29 '09 at 09:13
  • Thanks Marc, 1. I am interested to learn what does Application.Exit really do -- just make message pump stops and no more function (like terminate application)? 2. If Application.Exit does not have function to terminate Windows Forms application, why if we set other thread's property to backgourd threads, after calling Application.Exit will terminate the application? – George2 Jun 29 '09 at 11:15
  • It is a bit like using Close from the task-bar... http://msdn.microsoft.com/en-us/library/ms157894.aspx; it asks the message loops to commit suicide, but this can be cancelled, and doesn't account for other threads. – Marc Gravell Jun 29 '09 at 11:26
  • @Marc : How if we use `return;` from the '`catch` block ? Is it also not a good thing to terminate the application ? – Learner May 19 '11 at 10:17
  • @CSharpLearner it is about to exit the `Main` method *anyway* - adding a `return` won't change anything. And if you have non-background threads that are alive, it won't kill them either – Marc Gravell May 19 '11 at 12:11
  • @Marc: Thanks for you reply. I too had similar problem and when i used `return;` application did not continue as it was happening earlier with `Application.Exit`. So I thought using return should do the things. Am I totally wrong? – Learner May 19 '11 at 12:30
  • One issue I found with attempting to close Main is if you are closing your application as part of error handling and your error occurs in program.cs prior to the launch of Main. It will throw the application into an infinite error loop. – Scooter May 18 '19 at 16:21
17

Try the following:

Process.GetCurrentProcess().Kill();

Environment.Exit doesn't work with Winforms and Environment.FailFast throws its own exception.

eboix
  • 5,113
  • 1
  • 27
  • 38
4

If your application does not exit gracefully when you call Application.Exit there is (obviously) something that prevents it from doing so. This can be anything from a form setting e.Cancel = true in the FormClosing event, to a thread that is not a background thread that is still running. I would advice you to carefully research exactly what it is that keeps your process alive, and close that in a nice manner. That should make your application close nicely as well.

Typically, in a winforms application, it should be sufficient to close the main form.

Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343
  • You mean if all threads I created explicitly are marked as background, then application should exit after calling Application.Exit? – George2 Jun 29 '09 at 08:42
  • 1
    @George2: at least they will not keep the application alive by being foreground threads; there may be other reasons why it does not exit, but that is one place to check. I do think though that the the default value for Thread.IsBackground is false. Worth checking though. – Fredrik Mörk Jun 29 '09 at 08:45
  • Thanks @Fredrik, when I call Application.Exit, there are some non-backgroud threads running (they are created by myself explicitly using new Thread().Start()), do you think it is the reason of the explicitly created threads which blocks my application from exiting (when call Application.Exit())? – George2 Jun 29 '09 at 08:54
  • 1
    @George2: impossible for me to say, but if I was sitting with the code, and with the information that I have right now, that would be my first bet. – Fredrik Mörk Jun 29 '09 at 08:56
  • 1
    If that is true, consider adding some signaling mechanisms (EventWaitHandle) to notify those threads that they should end. Then join them and wait until they are finished. (That's better than making them background and killing them automatically) – vgru Jun 29 '09 at 10:14
  • Thanks Fredrik, "that would be my first bet" -- you mean set the threads which I create explicitly as backkground ones? – George2 Jun 29 '09 at 11:11
  • @Groo, good solution, 1. do you think the root cause of my issue -- Forms application does not terminate after calling Application.Exit is because of the threads I created expliicitly is not terminated? 2. If yes, I am interested to learn what does Application.Exit really do -- just make message pump stops and no more function? – George2 Jun 29 '09 at 11:14
3

I use

if (System.Windows.Forms.Application.MessageLoop)
{
   // Use this since we are a WinForms app
   System.Windows.Forms.Application.Exit();
}
else
{
   // Use this since we are a console app
   System.Environment.Exit(1);
}

from http://geekswithblogs.net/mtreadwell/archive/2004/06/06/6123.aspx

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Peter Gfader
  • 7,673
  • 8
  • 55
  • 56
  • Thanks Peter, 1. I am interested to learn what does Application.Exit really do -- just make message pump stops and no more function (like terminate application)? 2. If Application.Exit does not have function to terminate Windows Forms application, why if we set other thread's property to backgourd threads, after calling Application.Exit will terminate the application? – George2 Jun 29 '09 at 11:16
  • Hi George2, from MSDN: 1. Application.Exit Informs all message pumps that they must terminate, and then *closes all application windows* after the messages have been processed. 2. it has the function to terminate/close – Peter Gfader Jun 29 '09 at 11:21
1

I had the same problem when I discovered opening a new form/window within the program, and only HIDING that second form (not closing it), would prevent the main form from properly quitting via Application.Exit();

There are two solutions in this case. First is to simply use Close() on the main form instead of Application.Exit(). Second solution is to use the following code:

if (secondForm != null && !secondForm.IsDisposed) secondForm.Dispose();
Dan W
  • 3,520
  • 7
  • 42
  • 69
  • mainForm.Close() works for me. I had a hidden window that was causing this issue. What is the difference between Close() and Application.Exit() ? – Mark Lakata Jun 11 '13 at 23:30
-1

I found that simply all you need to do is insted of doing application.exit and all that you just have to do is put in End Simply enough the End command closes it

Leon
  • 11
  • 2
  • This doesn't really answer the question. Among other things, you don't say what `End` means. Are you referring to VB.NET? The question is about C#. – John Saunders Jun 19 '15 at 18:19